java实现文件转换成二进制存储与取出

一、功能描述:

将文件转成二进制数据放入数据库中,需要的时候,便可以取出安装与使用。

 

二、数据库:

建立一个数据库字段存放转成二进制的图片,这个字段有一个要求就是要设置成blob类型的

CREATE TABLE `save_image` (

  `id` int(50) NOT NULL AUTO_INCREMENT,

 `images` blob,

  PRIMARY KEY (`id`)

扫描二维码关注公众号,回复: 599107 查看本文章

三、转换文件成为二进制数据并保存的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();

}

}

猜你喜欢

转载自starbhhc.iteye.com/blog/2315882