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); } } }