There is a need to transfer the files originally stored in the database to the file system, so a simple program is written to complete this function, the Code is as follows:
Java code
Import java. io. BufferedOutputStream;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. PreparedStatement;
Import java. SQL. ResultSet;
Import org. dbunit. util. Base64;
Public class ReadBlob {
/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
Class. forName ("com. microsoft. sqlserver. jdbc. SQLServerDriver ");
Connection conn = DriverManager. getConnection (
"Jdbc: sqlserver: // localhost: 1433; DatabaseName = test1", "sa ",
"123456 ");
PreparedStatement ps = conn. prepareStatement ("select * from aa ");
ResultSet rs = ps.exe cuteQuery ();
While (rs. next ()){
String fileName = rs. getString ("FileName ");
String content = rs. getString ("Content ");
Byte [] byte_content = Base64.decode (content );
GenerateFile (byte_content, "D: \ doc", fileName );
}
Conn. close ();
}
/**
* Generate a file based on the byte array
*/
Public static void generateFile (byte [] bfile, String filePath, String fileName ){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
Try {
File dir = new File (filePath );
If (! Dir. exists () & dir. isDirectory ()){
Dir. mkdirs ();
}
File = new File (filePath + "\" + fileName );
Fos = new FileOutputStream (file );
Bos = new BufferedOutputStream (fos );
Bos. write (bfile );
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
If (bos! = Null ){
Try {
Bos. close ();
} Catch (IOException e1 ){
E1.printStackTrace ();
}
}
If (fos! = Null ){
Try {
Fos. close ();
} Catch (IOException e1 ){
E1.printStackTrace ();
}
}
}
}
}