mysql下大文本和二进制流的读写

   create table t1(
    id int primary key,
    content longtext
    );
   
//编写大文本的测试表


public class Test01 {
Connection  conn =null;
PreparedStatement  stmt =null ;


/**
* 文件的写入到数据库
*/
 public  void wirteFromText() {
 conn = DBCPUtil.getConnection();
 try {
stmt = conn.prepareStatement("insert into t1 values(2,?)");
File   file = new File("src/123.txt");
//将文件转换成字符流
Reader  reader = new FileReader(file);
//大文本的设置方式
stmt.setCharacterStream(1, reader,(int)file.length());
stmt.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
DBCPUtil.release(null, stmt, conn);
}
 }
      /**
       * 读取数据库的大文本,写入到指定文件中
       */
 public void  ReaderToText() {
 
 conn = DBCPUtil.getConnection();
 ResultSet rs = null;

 try{
stmt = conn.prepareStatement("select content from t1 where id=1");
rs = stmt.executeQuery();
if(rs.next()){
//将读取的大文本转化成字符流
   Reader in = rs.getCharacterStream(1);
   File file = new File("src/123.txt");
//    Writer out = new FileWriter(file);
   //将字符流写入到文件中
   Writer out = new FileWriter(file, true);
   char[] ch = new char[1024];
int len = 0;
while((len=in.read(ch))!=-1) {
out.write(ch,0,len);
}
   in.close();
   out.close();
}

} catch (Exception e) {
throw new RuntimeException(e);
}finally {
DBCPUtil.release(rs, stmt, conn);
}
 }
/**
 * 二进制流的输入输出  
   create table t2 (
    id  int ,
    content BLOB
    );
 */   
 @Test
 //写入数据库测试
 public void binaryToDb() {
 conn = DBCPUtil.getConnection();
 
 try {
stmt = conn.prepareStatement("insert into t2 values(1,?)");
File   file = new File("src/1.PNG");

InputStream  in = new FileInputStream(file);
stmt.setBinaryStream(1, in,in.available());
stmt.executeUpdate();

       }catch(Exception e) {
        throw new RuntimeException(e);
       }finally {
        DBCPUtil.release(null, stmt, conn);
       }
 
 }
 
 //读取二进制流测试
 @Test
 public void  binaryFromDb() {
 conn = DBCPUtil.getConnection();
 ResultSet rs = null;
 InputStream in =null;
 try {
stmt = conn.prepareStatement("select content from t2 where id = 1");
rs = stmt.executeQuery();
if(rs.next()) {
in = rs.getBinaryStream("content");
}
File   file = new File("d:/11235.png");

OutputStream  out = new FileOutputStream(file);
byte[]  ch = new byte[1024];
int len = -1;
while((len= in.read(ch))!=-1) {
out.write(ch,0,len);
}

in.close();
out.close();

} catch (Exception e) {
// TODO Auto-generated catch block
   throw new RuntimeException(e);
}
 
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值