Length for a byte array
I am trying to download a file from a MySQL database using JDBC, using the example below.
(The was posted to this forum by Koray Yersel on May 8, 2006)
I could use some help figuring out this line of the code: "byte[] buf = new byte[bBufLen];"
What should be the length of the byte Array, the variable "bBufLen" ?
Many thanks in advance
-- The original post:
here is my solution for writing and loading any kind of files in mysql db.
(tested with doc, jpeg, txt and pdf)
writing:
...PreparedStatement ps = conn.prepareStatement("insert into anlagen values('"+sendername.toString()+"','"+filename.toString() +"',?)");
File fileIn =new File("C:\\diso_temp\\" + filename);
int fileLength = (int) fileIn.length();
InputStream streamedFile =new FileInputStream(fileIn);
ps.setBinaryStream(1, streamedFile, fileLength);
ps.executeUpdate();
ps.close();
streamedFile.close();
...
reading / loading:
...
ResultSet rs = conn.createStatement().executeQuery("SELECT file,filename FROM anlagen");
while (rs.next()){
Blob blob = rs.getBlob("file");
String filename = rs.getString("filename");
OutputStream fwriter =new FileOutputStream("C:\\"+filename);
readFromBlob(blob, fwriter);
fwriter.close();
}
...
publicstaticlong readFromBlob(Blob blob, OutputStream out)
throws SQLException, IOException{
InputStream in = blob.getBinaryStream();
int length = -1;
long read = 0;
byte[] buf =newbyte[bBufLen];
while ((length = in.read(buf)) != -1){
out.write(buf, 0, length);
read += length;
}
in.close();
return read;
}

