从数据库中读取写入大文本
共有三种方法
1.使用流读取写入;
2.将数据作为一个大文本对象返回;
3.使用getString()获取。(将数据放入内存中,若数据过大,则内存容易崩溃)
文本文件--》字符流
1.写入,使用流:
public void insert() throws SQLException, FileNotFoundException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JdbcUtils.getConnection(); //JdbcUtils是一个获取数据库连接的工具类,下面另有一个关闭链接的工具类
String sql = "insert into lobb(id,resume) values(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, "001");
File file = new File("src/1.txt");
FileReader reader = new FileReader(file);
ps.setCharacterStream(2, reader,(int)file.length());
int num = ps.executeUpdate();
if(num > 0){
System.out.println("插入成功");
}
}finally{
JdbcUtils.closeAll(conn, ps, rs);
}
}
2.读取,使用流:
public void read() throws SQLException, IOException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JdbcUtils.getConnection();
String sql = "select * from lobb";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if(rs.next()){
rs.getString("id");
Reader reader = rs.getCharacterStream("resume");
FileWriter writer = new FileWriter("d://1.txt");
try{
int len = 0;
char buffer[] = new char[1024];
while((len = reader.read(buffer)) > 0){
writer.write(buffer, 0, len);
}
}finally{
if(reader != null){
reader.close();
}
writer.close();
}
}
}finally{
JdbcUtils.closeAll(conn, ps, rs);
}
}
影音图片--》字节流
1 public void insert() throws SQLException, IOException{ 2 Connection conn = null; 3 PreparedStatement ps = null; 4 ResultSet rs = null; 5 File file = new File("src/1.jpg"); 6 FileInputStream in = new FileInputStream(file); 7 try{ 8 conn = JdbcUtils.getConnection(); 9 String sql = "insert into lobbb(id,image) values(?,?)"; 10 ps = conn.prepareStatement(sql); 11 ps.setString(1, "001"); 12 ps.setBinaryStream(2, in, (int)file.length()); 13 ps.executeUpdate(); 14 }finally{ 15 JdbcUtils.closeAll(conn, ps, rs); 16 in.close(); 17 } 18 } 19 @Test 20 public void read() throws SQLException, IOException{ 21 Connection conn = null; 22 PreparedStatement ps = null; 23 ResultSet rs = null; 24 try{ 25 conn = JdbcUtils.getConnection(); 26 String sql = "select image from lobbb where id = ?"; 27 ps = conn.prepareStatement(sql); 28 ps.setString(1, "001"); 29 rs = ps.executeQuery(); 30 if(rs.next()){ 31 InputStream is = rs.getBinaryStream("image"); 32 File file = new File("d://1.jpg"); 33 OutputStream out = new FileOutputStream(file); 34 try{ 35 int len = 0; 36 byte buffer[] = new byte[1024]; 37 while((len = is.read(buffer)) > 0){ 38 out.write(buffer, 0, len); 39 } 40 }finally{ 41 if(is != null){ 42 is.close(); 43 } 44 out.close(); 45 } 46 } 47 }finally{ 48 JdbcUtils.closeAll(conn, ps, rs); 49 } 50 }