有这样一个需求,需要将原本存储在数据库中的文档转存至文件系统中,于是写了一个简单的程序完成此功能,代码如下:
Java代码
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();
}
/**
* 根据byte数组,生成文件
*/
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();
}
}
}
}
}
行业门户(
)文章,希望大家可以留言建议
阅读(1132) | 评论(0) | 转发(0) |