First, function Description:
The files are converted into binary data into the database, and when needed, they can be removed for installation and use.
Second, the database:
Create a database field to store the image into binary, this field has a requirement is to set the BLOB type of
[SQL]View Plaincopy
- CREATE TABLE ' save_image ' (
- ' ID ' int (a) is not NULL auto_increment,
- <span style="color: #FF0000;" > ' images ' blob</span>
- PRIMARY KEY (' id ')
- )
Third, convert the file into binary data and save the Java code:
[Java]View Plaincopy
- Public Void Save () throws SQLException
- {
- Connection=connectionmanager.getconn (); //Connect to the database and connect to your own database
- try {
- File file=new file ("d:\\1.jpg"); The file to convert
- FileInputStream inputstream=New FileInputStream (file);
- String sql="insert into save_image (images) VALUES (?)"; The SQL statements that are stored in the database must be executed with preparestatement
- Statement=connection.preparestatement (SQL);
- Statement.setbinarystream (1, InputStream, (int) file.length ());
- Statement.executeupdate ();
- } catch (FileNotFoundException e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- } catch (SQLException e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
Four, take out the data and restore the file to the local Java code:
[Java]View Plaincopy
- Reading a database binary file
- Public void Readerjpg () throws SQLException
- {
- Connection=connectionmanager.getconn (); //Connect to your own database!!!!!!!!
- String sqlstring="Select images from Save_image where id=4"; Read the binary code from the database to restore the file, here I read my own database ID 4 file
- File file=new file ("e:\\1.jpg"); Locally generated files
- if (!file.exists ())
- {
- try {
- File.createnewfile ();
- } catch (Exception e) {
- E.printstacktrace ();
- }
- }
- try {
- byte[] Buffer = new byte[4096*5];
- Statement=connection.preparestatement (sqlString);
- ResultSet = Statement.executequery ();
- if (Resultset.next ())
- {
- FileOutputStream outputstream = new FileOutputStream (file);
- InputStream IStream = Resultset.getbinarystream ("Images"); Go to field with Getbinarystream ()
- int size=0;
- While ((Size=istream.read (Buffer))!=-1)
- {
- SYSTEM.OUT.PRINTLN (size);
- Outputstream.write (Buffer,0,size);
- }
- }
- } catch (Exception e) {
- E.printstacktrace ();
- }
- }
Java implementation file conversion to binary storage and extraction