Java sqlserver text type field read method

  • 2020-04-01 01:26:57
  • OfStack

There is such a requirement that the original documents stored in the database need to be transferred to the file system, so I wrote a simple program to complete this function, the code is as follows:
Java code
 
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 { 
 
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(); 
} 
 
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(); 
} 
} 
} 
} 
} 

Related articles: