一、功能描述:
將文件轉成二進制數據放入數據庫中,需要的時候,便可以取出安裝與使用。
二、數據庫:
建立一個數據庫字段存放轉成二進制的圖片,這個字段有一個要求就是要設置成blob類型的
- CREATE TABLE `save_image` (
- `id` int(50) NOT NULL AUTO_INCREMENT,
- <span style="color:#FF0000;">`images` blob</span>,
- PRIMARY KEY (`id`)
- )
三、轉換文件成為二進制數據並保存的Java代碼:
- public void save() throws SQLException
- {
- connection=connectionManager.getconn();//連接數據庫的操作,這里自己連接自己的數據庫
- try {
- File file=new File("D:\\1.jpg");//要轉換的文件
- FileInputStream inputStream=new FileInputStream(file);
- String sql="insert into save_image(images) values(?)";//存入數據庫的SQL語句在執行的時候一定要用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();
- }
- }
四、取出數據並還原文件到本地的java代碼:
- //讀取數據庫二進制文件
- public void readerJpg() throws SQLException
- {
- connection=connectionManager.getconn();//自己連接自己的數據庫!!!!!!!!
- String sqlString="select images from save_image where id=4";//從數據庫中讀出要還原文件的二進制碼,這里我讀的是自己的數據庫id為4的文件
- File file=new File("E:\\1.jpg");//本地生成的文件
- 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");//去字段用getBinaryStream()
- int size=0;
- while((size=iStream.read(Buffer))!=-1)
- {
- System.out.println(size);
- outputStream.write(Buffer,0,size);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }