有这样一个需求,需要将原本存储在数据库中的文档转存至文件系统中,于是写了一个简单的程序完成此功能,代码如下:
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();
}
}
}
}
}
希望与广大网友互动??
点此进行留言吧!