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

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;//定义一个结果集
	@Test
	public void test() throws Exception{
		//调用方法1
		method1();
		//调用方法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();
		//使用while
		while(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();
		//使用while
		while(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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值