【问题标题】:Reading an array from file. (java)从文件中读取数组。 (爪哇)
【发布时间】:2015-08-20 12:22:30
【问题描述】:

你好,这是我从文件中读取的代码

case 11: {
    String line;
    String temp[];
    System.out.println("Podaj nazwę pliku z jakiego odczytać playlistę.");
    nazwa11 = odczyt.next();
    try {

        FileReader fileReader = new FileReader(nazwa11);

        BufferedReader bufferedReader = new BufferedReader(fileReader);
        playlists.add(new Playlist(bufferedReader.readLine()));
        x++;
        while((line = bufferedReader.readLine())!=null){
            String delimiter = "|";
            temp = line.split(delimiter);
            int rok;
            rok = Integer.parseInt(temp[2]);
            playlists.get(x).dodajUtwor(temp[0], temp[1], rok);


        }


        bufferedReader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Nie znaleziono pliku: '" + nazwa11 + "'");
    } catch (IOException ex) {
        System.out.println("Error reading file '" + nazwa11 + "'");
    }
    break;
}

示例文件如下所示:

Pop
Test|Test|2010
Test1|Test1|2001

给我错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "s"

为什么我的 line.split 在找到“|”时没有拆分?我猜它分裂了t-e-s,有什么提示吗?

【问题讨论】:

  • 您的分隔符被评估为正则表达式,因此您需要转义管道:delimiter = "\\|";

标签: java string file split int


【解决方案1】:

管道字符“|”是执行匹配时具有特殊含义的元字符之一。

page 为您提供了这些特殊字符及其含义的完整列表。

所以,在你的程序中,修改下面这行,

String delimiter = "|";

String delimiter = "\\|";

这将为您提供您想要的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多