简体   繁体   中英

Reading an array from file. (java)

Hello it is my code to read from file

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

Example file looks like this:

Pop
Test|Test|2010
Test1|Test1|2001

Gives me error

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

Why my line.split doesn't split when it finds "|"? I guess it splits tes, any tips?

The pipe character "|" is one of the meta characters that carries a special meaning while performing the match.

This page gives you the complete lists of these special characters and their meanings.

So, in your program, modify the following line,

String delimiter = "|";

to

String delimiter = "\\|";

This will give you the result that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM