There is a need to transfer documents originally stored in the database to the file system, so I wrote a simple program to complete this function. The code is as follows:
Java code
Copy the 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 files based on 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();
}
}
}
}
}