使用java将数据库文件复制到本地磁盘中

来源:互联网 发布:淘宝售前客服是做什么? 编辑:程序博客网 时间:2024/05/29 17:53
package com.starry.exersise;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.sql.Blob;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.sql.rowset.serial.SerialBlob;import org.apache.commons.io.IOUtils;import org.junit.Test;/** * 将mysql中的MP3文件复制到本地磁盘中 *  * 方法一: * 整体思路1:新建一个input输入流读取MP3文件内容 * 2:将读取到的mp3文件写入byte数组中 * 3:连接数据库,将文件写入数据库中(数据类型为blob类型) * 方法二: 第三方类库中的方法 *  * @author Starry * */public class InputMp3 {//定义需要使用的变量static Connection con=null;//创建一个连接数据库的对象static PreparedStatement pst=null;//定义一个向数据库发送sql与语句的对象\static ResultSet res=null;//定义一个结果集@Testpublic void test() throws Exception{//调用方法1method1();//调用方法2//method2();}/** * 方法一 * @throws IOException * @throws SQLException */public void method1() throws Exception{//创建一个connection对象(后面的是我自己定义的一个工具类,复制不可用)con=MyJDBCUtil.getConnection();//定义一个sql语句String sql="select 文件 from table2 where id=1";//创建一个preparedstatement对象pst=con.prepareStatement(sql);//获取结果集res=pst.executeQuery();//使用whilewhile(res.next()){Blob b=res.getBlob("文件");Blob blob=new SerialBlob(b);//创建一个input 来获取blob对象InputStream ins=blob.getBinaryStream();//使用buffered 加快速度BufferedInputStream bis=new BufferedInputStream(ins);//创建一个输出流  写入要复制到的位置BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("C:\\新建文件夹 (2)\\copybb.mp3"));//创建一个byte数组 byte[] array=new byte[1024];int len=0;while((len=bis.read(array))!=-1){bos.write(array, 0, len);}//关闭流bis.close();bos.close();}}/** * 方法二 * @throws IOException * @throws SQLException */public void method2() throws Exception{//创建一个connection对象(后面的是我自己定义的一个工具类,复制不可用)con=MyJDBCUtil.getConnection();//定义一个sql语句String sql="select 文件 from table2 where id=1";//创建一个preparedstatement对象pst=con.prepareStatement(sql);//获取结果集res=pst.executeQuery();//使用whilewhile(res.next()){Blob b=res.getBlob("文件");Blob blob=new SerialBlob(b);//创建一个input 来获取blob对象InputStream ins=blob.getBinaryStream();//使用buffered 加快速度BufferedInputStream bis=new BufferedInputStream(ins);//创建一个输出流  写入要复制到的位置BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("C:\\新建文件夹 (2)\\copybb.mp3"));//第三方类库的形式int result = IOUtils.copy(bis, bos);System.out.println("copy了多少字节?" + result);}}}
starry.每天进步一点点。

阅读全文
0 0
原创粉丝点击