我有这行代码。而 numbers.txt 有这些数字的字符串:123456789。运行它会打印:235689。为什么? .read() 做什么?当“while(fin.read() > -1 )”为真时?还有关于为什么我在不使用它时出现 IOException 错误的异常,因为程序是正确的?
import java.io.*;
public class Read {
public static void main(String[] args) throws Exception {
FileReader fin = new FileReader("numbers.txt");
while(fin.read() > -1 ){
System.out.print((char) fin.read());
System.out.print((char) fin.read());
}
fin.close();
}
}
最佳答案
您正在丢弃每三个字符。我建议存储您读取的字符并打印它。
for(int ch; (ch = fin.read()) > -1; )
System.out.print((char) ch);
我建议你像这样使用 BufferedReader
try(BufferedReader br = new BufferedReader(new FileReader("numbers.txt"))) {
for(String line; (line = br.readLine()) != null; )
System.out.println(line);
} // closes the br
关于Java .read() 函数返回什么?和Java IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099427/