Java reads text fields

Source: Internet
Author: User

There is a need to transfer the files originally stored in the database to the file system, so a simple program is written 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 {
 
/**
* @ 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.exe cuteQuery ();
 
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 a file based on the 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 ();
}
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.