关于输入流与输出流

在这里需要强调的一点是:

输入流和输出流,差别在于出和入,是相对于程序而言的。“输入流式得到数据,输出流是输出数据”。输入是程序得到外部数据,输出是程序向外部传输数据,二者没有必然的联系,都是流,差别是方向不同,也就是说,程序可以只有输入流而没有输出流,或者只有输出流而没有输入流。

 

伪代码如下:

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

}



}
View Code

 

你可能感兴趣的:(输入流)