关于输入流与输出流

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

 

伪代码如下:

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") ; //获取相应的文件位置

 

这里对数据库中对图片的存储也说明一下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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();
}
 
}

 字节流和字符流:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值