问题描述
File readFile = new File("acc\\10001.txt");
protected void readData(File file){
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while(reader.read() != -1){
System.out.println(reader.readLine());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null,ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,ex);
}
}
方法位于Main类的构造函数中。启动项目时,控制台会显示(例如):“ est”代替“ Test”,“ 0001”代替“ 10001”。
它适用于所有字符串和整数。
我们非常感谢您的帮助。
解决方法
您的代码段:
while(reader.read() != -1){
System.out.println(reader.readLine());
}
每次评估while条件时都会读取一个字符(read()
被调用并且it reads next character。
使用更好的方法更改代码:
String line="";
while ((line=reader.readLine()) != null) { //variable line gets assigned with value and then it's checked against null
System.out.println(line);
}