package test;import java.io.FileInputStream;
import java.io.InputStream;public class test1 {
public static void main(String[] args) {
try {
InputStream in= new FileInputStream("d:/haha.txt");
int n;

while((n=in.read())!=-1){
        char c=(char)n;
        System.out.print(c);

}

// while((in.read())!=-1){
//         char c=(char)(in.read());
//         System.out.print(c);
//
// }


           in.close();

} catch (Exception e) {

e.printStackTrace();
}

}}
以上代码,为什么不能按照注释的写,感觉其实一样的,为什么就错了呢

解决方案 »

  1.   

    每调用一次reed()都会读一个字符,照注释的写法,每次循环都读了两个字符,但只有一个被输出
      

  2.   

    in.read()只要调用一次就会读,你判断那里调了一次,下面又调用了一次,所以这样就是两次了
      

  3.   

    这里的IO 是按流(stream)的方式读取,这个读取过程是不可逆的。
    比如流是 123456
    第一次调用read()方法读取的是1
    第二次调用read()方法读取的是2
    第三次调用read()方法读取的是2
    一直到最后读完 read 方法返回-1如果你确实有反复读取的需求,有些流是有回退功能的,类似如下代码。
    看看java io的所有接口就知道哪些类有这个回退功能了。
    如果你理解装饰器模式(decorator)就能更好的理解java的io包。
    try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(""));
    buf.(arg0);
    buf.reset();
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }还有下次发帖子时,把代码用  包起来,这样就有关键字高亮等功能了,看起来更容易些。
    比如我发的这段代码。
      

  4.   

    这么多人回了。多读一次了。/**
         * Reads the next byte of data from the input stream. The value byte is
         * returned as an <code>int</code> in the range <code>0</code> to
         * <code>255</code>. If no byte is available because the end of the stream
         * has been reached, the value <code>-1</code> is returned. This method
         * blocks until input data is available, the end of the stream is detected,
         * or an exception is thrown.
         *
         * <p> A subclass must provide an implementation of this method.
         *
         * @return     the next byte of data, or <code>-1</code> if the end of the
         *             stream is reached.
         * @exception  IOException  if an I/O error occurs.
         */
        public abstract int read() throws IOException;