java 在java中,一次读入一个字符时,如何确定EOF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15045424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In java, when reading in a file one character at a time, how do I determine EOF?
提问by art3m1sm00n
I am having to read in a while and use an algorithm to code each letter and then print them to another file. I know generally to find the end of a file you would use readLine and check to see if its null. I am using a bufferedReader. Is there anyway to check to see if there is another character to read in? Basically, how do I know that I just read in the last character of the file?
我不得不阅读一段时间并使用算法对每个字母进行编码,然后将它们打印到另一个文件中。我通常知道要找到文件的结尾,您将使用 readLine 并检查它是否为空。我正在使用一个缓冲阅读器。无论如何要检查是否有另一个字符可以读入?基本上,我怎么知道我刚刚读入了文件的最后一个字符?
I guess i could use readline and see if there was another line if I knew how to determine when I was at the end of my current line.
我想我可以使用 readline 并查看是否还有另一行,如果我知道如何确定我何时处于当前行的末尾。
I found where the File class has a method called size() that supposidly turns the length in bytes of the file. Would that be telling me how many characters are in the file? Could i do while(charCount<length)
?
我发现 File 类有一个名为 size() 的方法,它可以转换文件的字节长度。这会告诉我文件中有多少个字符吗?我可以while(charCount<length)
吗?
回答by gd1
I don't exactly understand what you want to do. I guess you may want to read a file character by character. If so, you can do:
我不完全明白你想做什么。我猜您可能想逐个字符地读取文件。如果是这样,你可以这样做:
FileInputStream fileInput = new FileInputStream("file.txt");
int r;
while ((r = fileInput.read()) != -1) {
char c = (char) r;
// do something with the character c
}
fileInput.close();
FileInputStream.read()
returns -1
when there are no more characters to read. It returns an int
and not a char
so a cast is mandatory.
FileInputStream.read()
-1
当没有更多字符要读取时返回。它返回一个int
而不是一个char
所以强制转换是强制性的。
Please note that this won't work if your file is in UTF-8 format and contains multi-byte characters. In that case you have to wrap the FileInputStream
in an InputStreamReader
and specify the appropriate charset. I'm omitting it here for the sake of simplicity.
请注意,如果您的文件是 UTF-8 格式并且包含多字节字符,这将不起作用。在这种情况下,您必须将 包装FileInputStream
在 an 中InputStreamReader
并指定适当的字符集。为了简单起见,我在这里省略了它。
回答by Saquib Mian
From my understanding, buffers will return -1 if there are no characters left. So you could write:
根据我的理解,如果没有剩余字符,缓冲区将返回 -1。所以你可以写:
BufferedInputStream in = new BufferedInputStream(new FileInputStream("filename"));
while (currentChar = in.read() != -1) {
//do something
}
in.close();