package example;
import java.io.*;
import java.sql.*;
public class Test {
public static void main(String[] args) throws Exception {
//write();
read();
}
public static void write() throws Exception {
Connection connection = getConnection();
if(connection == null) {
return;
}
String sql = "insert into t2(pic) values(?)";
String filePath = "/mnt/hda6/doc/Flower2.jpg";
FileInputStream fis = new FileInputStream(filePath);
PreparedStatement pst = connection.prepareStatement(sql);
pst.setBinaryStream(1, fis, fis.available());
pst.execute();
pst.close();
pst.close();
}
public static void read() throws Exception {
Connection connection = getConnection();
if(connection == null) {
return;
}
String sql = "select pic from t2";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(sql);
byte[] buffer = new byte[1024];
while(rs.next()) {
Blob b = rs.getBlob("pic");
int size = (int) b.length();
InputStream ips = b.getBinaryStream();
FileOutputStream fos = new FileOutputStream("/home/x.jpg");
while( (size = ips.read(buffer)) != -1) {
fos.write(buffer, 0, size);
}
fos.close();
ips.close();
}
rs.close();
st.close();
connection.close();
}
public static Connection getConnection() {
Connection connection = null;
try {
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/mydb?useUnicode=true&characterEncoding=GBK";
String user = "root";
String password = "";
Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, password);
} catch(Exception e) {
e.printStackTrace();
}
return connection;
}
}
如何利用java io stream把读出的byte[] buffer写入一个图片文件中?
最新推荐文章于 2022-10-03 16:12:07 发布