import java.io.*; import java.util.*; import java.sql.*; public class BlobTestInsert { private Connection con = null; public BlobTestInsert() { try { Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/files", "blind", ""); if (con != null) { System.out.println("Connected to database system.\n"); } } catch (SQLException e) { System.out.println(e.getMessage()); System.out.println("Could not connect to database system.\n"); } catch (ClassNotFoundException e) { System.out.println("Class not found...:-(\n"); } } private void store(String filename) { PreparedStatement ps = null; ResultSet r = null; File file = new File(filename); byte[] l_buf = new byte[8000]; int l_size = 0; System.out.println("store start " + System.currentTimeMillis() + " file.name:" + file.getName() + "file.length:"+file.length()); try { FileInputStream fis = new FileInputStream(file); con.setAutoCommit(false); ps = con.prepareStatement( "INSERT INTO tblob1 VALUES (?, ?, ?);"); while (l_size < file.length()) { fis.read(l_buf); ps.setString(1, filename); ps.setInt(2,l_size); ps.setBytes(3,l_buf); l_size += 8000; ps.executeUpdate(); } ps.close(); fis.close(); con.commit(); System.out.println("store end " + System.currentTimeMillis()); } catch (SQLException sqle) { System.err.println("Store content: " + sqle.getMessage()); } catch (IOException ioe) { } } private void retrieve(String filename) { Statement s = null; ResultSet r = null; int byteSum = 0; byte[] buffer = new byte[8000]; try { System.out.println("read start " + System.currentTimeMillis() + " Trying to write: " +filename + "test"); FileOutputStream out = new FileOutputStream(filename + "test"); con.setAutoCommit(false); s = con.createStatement(); r = s.executeQuery("SELECT data FROM tblob1 WHERE filename = '" + filename +"' order by lastbyte"); if (r != null) { while (r.next()) { buffer = r.getBytes(1); out.write(buffer); byteSum += buffer.length; } } out.close(); System.out.println("read end " + System.currentTimeMillis() + " bytes written: " + byteSum); con.commit(); } catch (SQLException sqle) { System.err.println("Retrieve content: " + sqle.getMessage()); } catch (Exception ioe) { System.err.println("Writing stuff: " + ioe.getMessage()); } } public static void main(String[] args) { BlobTestInsert bt = new BlobTestInsert(); bt.store(args[0]); bt.retrieve(args[0]); } }