There is a need to dump documents originally stored in the database into the file system, so a simple program is written to complete this function, as follows:
Java code
Copy Code code as follows:
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.executequery ();
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 file according to 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 ();
}
}
}
}
}