javasqlservertext类型字段读取⽅法
有这样⼀个需求,需要将原本存储在数据库中的⽂档转存⾄⽂件系统中,于是写了⼀个简单的程序完成此功能,代码如下: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 = Connection(
"jdbc:sqlserver://localhost:1433;DatabaseName=test1", "sa",
"123456");
PreparedStatement ps = conn.prepareStatement("select * from aa");
ResultSet rs = ps.executeQuery();
()){
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(!ists()&&dir.isDirectory()){
dir.mkdirs();
}
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();
}
}
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论