How to use Java Io stream to write read byte [] buffer into an image file?

Source: Internet
Author: User

Package example;

Import java. Io .*;
Import java. SQL .*;

Public class test {

Public static void main (string [] ARGs) throws exception {
// Write ();
Read ();
}

Public static void write () throws exception {
Connection connection = getconnection ();
If (connection = NULL ){
Return;
}

String SQL = "insert into T2 (PIC) values (?) ";
String filepath = "/mnt/hda6/doc/flower2.jpg ";
Fileinputstream FCM = new fileinputstream (filepath );
Preparedstatement PST = connection. preparestatement (SQL );
Pst. setbinarystream (1, fiis, fiis. Available ());
Pst.exe cute ();
Pst. Close ();
Pst. Close ();
}

Public static void read () throws exception {
Connection connection = getconnection ();
If (connection = NULL ){
Return;
}
String SQL = "select pic from t2 ";
Statement ST = connection. createstatement ();
Resultset rs = st.exe cutequery (SQL );
Byte [] buffer = new byte [1024];

While (Rs. Next ()){
Blob B = Rs. getblob ("pic ");
Int size = (INT) B. Length ();
Inputstream IPS = B. getbinarystream ();
Fileoutputstream Fos = new fileoutputstream ("/home/x.jpg ");

While (size = IPs. Read (buffer ))! =-1 ){
FOS. Write (buffer, 0, size );
}
FOS. Close ();
IPS. Close ();

}

Rs. Close ();
St. Close ();
Connection. Close ();
}

Public static connection getconnection (){

Connection connection = NULL;

Try {
String driverclass = "com. MySQL. JDBC. Driver ";
String url = "JDBC: mysql: // localhost/mydb? Useunicode = true & characterencoding = GBK ";
String user = "root ";
String Password = "";

Class. forname (driverclass );
Connection = drivermanager. getconnection (URL, user, password );

} Catch (exception e ){
E. printstacktrace ();
}

Return connection;
}
}

Related Article

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.