Monday, September 5, 2011

Image Write into Folder

import java.sql.*;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.File;

public class WriteImages {
    public static void main(String args[]){
        String dcode = "chn";
        String tname = "sup";
        String connectionURL = "jdbc:postgresql://localhost:5432/db";
        String imageQuery    = "select uidno, photo from "+dcode+".e_"+tname+" where photo is not null limit 10";
        String imageQueryphoto = "select uidno, photo from "+dcode+".e_"+tname+"_photo where photo is not null limit 10";
        try{
            Class.forName("org.postgresql.Driver").newInstance();
            Connection con = DriverManager.getConnection(connectionURL,"uname","pwd");
            Statement st1=con.createStatement();
            ResultSet rs1 = st1.executeQuery(imageQuery);
            while (rs1.next())
            {
                long uidNo   = rs1.getLong(1);
                InputStream imageStream = rs1.getBinaryStream(2);
                String imageName = "/tmp/"+uidNo+"image.jpg";
                FileOutputStream f = new FileOutputStream(imageName);
                byte buff[] = new byte[1024];
                     int l;
                      while ((l = imageStream.read(buff)) > 0)
                        {
                            f.write(buff, 0, l);
                        }
                        f.close();
                        File fl = new File("/tmp/"+uidNo+"image.jpg");
                        System.out.println("File 1 Created and length is="+fl.length());
            }
            Statement st2=con.createStatement();
            ResultSet rs2 = st2.executeQuery(imageQueryphoto);
            while(rs2.next()){
                long uidNo2   = rs2.getLong(1);
                InputStream imageStream2 = rs2.getBinaryStream(2);
                String imageName = "/tmp/"+uidNo2+"image2.jpg";
                   
                FileOutputStream f2 = new FileOutputStream(imageName);
                     byte buff2[] = new byte[1024];
                          int l2;
                           while ((l2 = imageStream2.read(buff2)) > 0)
                             {
                                 f2.write(buff2, 0, l2);
                             }
                             f2.close();
                             File fl2 = new File("/tmp/"+uidNo2+"image2.jpg");
                             System.out.println("File 2 Created and length is="+fl2.length());
                }
            rs2.close();
            st2.close();
            rs1.close();
            st1.close();
            con.close();
      }
      catch (Exception e){
         e.printStackTrace();
      }
   }
}

No comments:

Post a Comment