英文:
FileReader "eats" each first letter
问题
我有一段代码:
File readFile = new File("acc\001.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, null, ex);
}
}
这个方法位于Main类的构造函数中。当启动项目时,控制台显示(例如):“est”而不是“Test”,“0001”而不是“10001”。
它适用于所有的字符串和整数。
每一点帮助都受到赞赏。
英文:
I have a code:
File readFile = new File("acc\001.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, null, ex);
}
}
Method is in constructor of the Main class. When starting the project, console shows (e.g.): "est" instead of "Test", "0001" instead of "10001".
It works for all strings and integers.
Each help is appreciated.
答案1
得分: 1
你的片段:
while(reader.read() != -1){
System.out.println(reader.readLine());
}
在每次评估 while 条件时读取一个字符(调用 read()
并读取下一个字符)。
使用更好的方法修改你的代码:
String line = "";
while ((line = reader.readLine()) != null) { //变量 line 被赋值然后与 null 进行比较
System.out.println(line);
}
英文:
Your snippet:
while(reader.read() != -1){
System.out.println(reader.readLine());
}
reads one character every time the while condition is evaluated (read()
gets invoked and it reads next character.
Change your code with better approach:
String line="";
while ((line=reader.readLine()) != null) { //variable line gets assigned with value and then it's checked against null
System.out.println(line);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论