讨教个基础 OutputStream和InputStream 的read 和 write问题

J2EE 码拜 8年前 (2016-03-14) 1043次浏览
     URL website = new URL(url);                                          // –url 为一个图片的链接
URLConnection con = website.openConnection();
con.setConnectTimeout(5000);
InputStream is = con.getInputStream();

File p1 =   new File(“G:\P1.jpg”);
File p2 =   new File(“G:\P2.jpg”);
OutputStream os1 = new FileOutputStream(p1);
OutputStream os2 = new FileOutputStream(p2);
byte[] bs= new byte[1024];
int len;

while((len = is.read(bs)) !=-1)
os1.write(bs,0,len);                              //    —  P1.jpg  下载正常

while((len = is.read(bs)) !=-1)                     //      问题2 –is 不能用重复 read吗?
os2.write(bs,0,len);                               //      问题1 —  P2.jpg 大小为0字节, 不能正常显示;为什么?

解决方案

40

InputStream相当于带一个标记的管道,每读一点就往后移动标记值。你第一遍读完,标记已经移到最后,第二次再读也没什么东西了

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明讨教个基础 OutputStream和InputStream 的read 和 write问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)