InputStream使用read()方法 时,判断尾标记许主意的问题

来源:互联网 发布:感觉身体被掏空 知乎 编辑:程序博客网 时间:2024/04/28 06:57


先看下面一段代码:

[java] view plaincopyprint?
  1. //同过判断文件的结尾来读取文件  
  2. import java.io.File;  
  3. import java.io.InputStream;  
  4. import java.io.FileInputStream;  
  5. public class InputStreamDemo02  
  6. {  
  7.     public static void main(String args[]) throws Exception{  
  8.         File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");  
  9.         InputStream in = new FileInputStream(f);  
  10.         byte b[] = new byte[1024];  
  11.         int len = 0;  
  12.         int temp=0;          //所有读取的内容都使用temp接收  
  13.         while((temp=in.read())!=-1){    //当没有读取完时,继续读取  
  14.             b[len]=(byte)temp;  
  15.             len++;  
  16.         }  
  17.         in.close();  
  18.         System.out.println(new String(b,0,len));  
  19.     }  
  20. }  

运行结果为:Hello,java

在此代码中如果我不使用temp进行接收每次读取的内容,而直接操作每次读取的内容会怎么样呢?看下面的代码:

[java] view plaincopyprint?
  1. //同过判断文件的结尾来读取文件,不使用temp对读取的每个字节进行接收时,对比InputStreamDemo01.java  
  2. import java.io.File;  
  3. import java.io.InputStream;  
  4. import java.io.FileInputStream;  
  5. public class InputStreamDemo03  
  6. {  
  7.     public static void main(String args[]) throws Exception{  
  8.         File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");  
  9.         InputStream in = new FileInputStream(f);  
  10.         byte b[] = new byte[1024];  
  11.         int len = 0;  
  12.         //int temp=0;  
  13.         while((in.read())!=-1){    //当没有读取完时,继续读取  
  14.             b[len]=(byte)in.read();       
  15.             len++;  
  16.         }  
  17.         System.out.println(new String(b,0,len));  
  18.     }  
  19. }  

运行结果为:el,aa

 

造成这一结果的原因是什么?

观察可以发现,运行结果是跳跃的,每一个内容与上一个内容都间隔了一个字符。再阅读代码发现:in.read()被调用的两次,所以原因也就出来了:原因是有两次调用in.read(),in.read()是读取下一字节,导致b[]中存储的是跳跃的,即每次存入其中的都与上一个内容相差一个字节。问题并不复杂,重要的是自己书写时可能会造成这样的错误,所以一定要使用temp对读取的内容进行接收,同时只操作temp。发现问题和解决问题时,细心耐心很重要。

0 0
原创粉丝点击