FileReader “吃掉” 每个第一个字母

huangapple go评论68阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2020年8月31日 00:16:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63659508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定