在這里需要強調的一點是:
輸入流和輸出流,差別在於出和入,是相對於程序而言的。“輸入流式得到數據,輸出流是輸出數據”。輸入是程序得到外部數據,輸出是程序向外部傳輸數據,二者沒有必然的聯系,都是流,差別是方向不同,也就是說,程序可以只有輸入流而沒有輸出流,或者只有輸出流而沒有輸入流。
偽代碼如下:
OutputStream oos = null; //
InputStream iis = null; // 從本地讀入
iis = new BufferedInputStream(new FileInputStream(new File(filename)));// 通過輸入流讀取圖片數據,其中filename代表文件路徑
byte[] bs = new byte[1024];
int length = -1;
while ((length = iis.read(bs, 0, bs.length)) != -1) {//如果是輸出的話,這里就是write函數了
oos.write(bs, 0, length);
oos.flush();
}
但是由於開發者的系統不同以及電腦磁盤位置不同
所以這里可以用到一個常用的Java系統屬性
String s=System.getProperty("user.home") ; //獲取相應的文件位置
這里對數據庫中對圖片的存儲也說明一下:
public void saveCommodity(List<String> sqls, List<List<Object>> params,String cid, String filename) throws SQLException {
DBHelper db = new DBHelper();
// 在根據新編號查出cphoto這個列,以流的方式插入
String sql2="select photo from tb_record where id=? for update";
//String sql1 = "update tb_record set photo=? where RECORD_NUMBER=? ";//
Connection con = null;
try {
con = db.getcon();
con.setAutoCommit(false);
PreparedStatement pstmt = null;
for (int i = 0; i < sqls.size(); i++) {
String sql = sqls.get(i);
pstmt = con.prepareStatement(sql);
List<Object> param = params.get(i);
for (int j = 0; j < param.size(); j++) {
pstmt.setObject(j + 1, param.get(j));
}
pstmt.executeUpdate();
}
if (filename != null && !filename.equals("")) {
pstmt = con.prepareStatement(sql2);
pstmt.setString(1, cid);
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.next()) {
OutputStream oos = null; // 向數據庫中輸入圖片
InputStream iis = null; // 從本地讀入
oracle.sql.BLOB b = (oracle.sql.BLOB) rs.getBlob(1);
oos = b.getBinaryOutputStream(); // 從結果集中取出輸入流,用於向數據庫些數據
iis = new BufferedInputStream(new FileInputStream(new File(
filename)));
// 通過輸入流讀取圖片數據
byte[] bs = new byte[1024];
int length = -1;
while ((length = iis.read(bs, 0, bs.length)) != -1) {
oos.write(bs, 0, length);
oos.flush();
}
}
}
con.commit();
} catch (Exception e) {
e.printStackTrace();
con.rollback();
} finally {
con.setAutoCommit(true);
con.close();
}
}
字節流和字符流:

