读取文件时出现异常,分割字符为 “|”。

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

Exception read data from file while split character "|"

问题

Your translated code:

public void loadDataFromFile(ArrayList<Book> list, String fileName) {
    File f = new File(fileName);
    try {
        Scanner sc = new Scanner(f);
        while (sc.hasNext()) { 
            String perLine = sc.nextLine(); //get data per line
            String txt[] = perLine.split(" ");
            list.add(new Book(txt[0], txt[1], Integer.parseInt(txt[2]), Double.parseDouble(txt[3])));
        }
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
}

Please note that I've changed the split delimiter from "|" to " ", as mentioned in your explanation, for it to work correctly.

英文:
public void loadDataFromFile(ArrayList&lt;Book&gt; list, String fileName) {
    File f = new File(fileName);
    try {
        Scanner sc = new Scanner(f);
        while (sc.hasNext()) { 
            String perLine = sc.nextLine(); //get date per line
            String txt[] = perLine.split(&quot;|&quot;);
            list.add(new Book(txt[0], txt[1], Integer.parseInt(txt[2]), Double.parseDouble(txt[3])));
        }
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
}

My function read data from file and add data to arraylist. But when I run this function, it have bug like this picture
读取文件时出现异常,分割字符为 “|”。
<br>My file is book.txt and data of this file is
A2|Hoa|22|50.3. If i try split at character &quot;|&quot;, it will have bug like this picture. But if i change data of file to A2 Hoa 22 50.3 and split at &quot; &quot; it working.

答案1

得分: 2

在Java中,Stringsplit()方法使用正则表达式作为参数工作,因为|在正则表达式中是特殊字符,所以你需要使用\\|来转义它,如下所示:perLine.split("\\|");

英文:

In java String split() method work's with regex as argument since '|' is special character in regex you need to escape it with \\ as folowing perLine.split(&quot;\\|&quot;);

huangapple
  • 本文由 发表于 2020年7月28日 12:18:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63126955.html
匿名

发表评论

匿名网友

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

确定