简体   繁体   English

Java中的阅读器在字符缓冲区的情况下如何内部工作?

[英]How does reader in Java internally work in case of character buffer?

public class ReadFileUsingFileReader {

public static void main(String[] args) {
        String path = "D:\\sticky_notes.txt";
        readFileUsingFileReader(path);
    }

    public static void readFileUsingFileReader(String file) {

        try {
            //read the file
            FileReader reader = new FileReader(file);
            char[] buffer = new char[1024];
            int noOfCharsRead = reader.read(buffer);
            while (noOfCharsRead != -1) {
                System.out.println(String.valueOf(buffer, 0, noOfCharsRead));
                noOfCharsRead = reader.read(buffer);
            }
            reader.close();
     } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Here the variable "reader" reads the first 1024 characters from the file and save it into the buffer. 在这里,变量“ reader”从文件中读取前1024个字符,并将其保存到缓冲区中。 Now again in the while loop, it reads the next 1024 characters. 现在再次在while循环中,它读取接下来的1024个字符。 My question is how does in the second time reader comes to know from which index it should start reading the next characters. 我的问题是,读者第二次如何知道应该从哪个索引开始读取下一个字符。 Is there some kind of flag, if yes how to access it. 是否有某种标志,如果是,如何访问它。

This is the purpose of classes that implements the concept of opened files . 这是实现打开文件概念的类的目的。 There is an underlying structure which contains the current position, just like a bookmark when you read a book. 有一个包含当前位置的底层结构,就像您读书时的书签一样。 Java FileReader doesn't provide you access to it because Readers almost just let you read from the beginning to the end. Java FileReader无法为您提供访问权限,因为Readers几乎只允许您从头到尾阅读。 So the current position is exactly the number of bytes you actually read. 因此,当前位置恰好是您实际读取的字节数。

But you can have access to it if you use a RandomAccessFile on which you can call long getFilePointer() and void seek(long position) methods. 但是,如果使用RandomAccessFile可以访问它,可以在其上调用long getFilePointer()void seek(long position)方法。 RandomAccessFile is the only file manipulation class that let you control where input/output will occur. RandomAccessFile是唯一使您可以控制输入/输出发生位置的文件操作类。

---- EDIT (thanks EJP) ---- ----编辑(感谢EJP)----

This is true only for package java.io . 仅对于包java.io There exists another advanced IO package java.nio for which things are slightly different. 还有另一个高级IO包java.nio ,它们的功能略有不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM