使用FileReader

时间:2015-12-23 16:38:53

标签: java bufferedreader filereader parseint numberformatexception

我有一个包含几行的纯文本文件。每一行都以id:

开头
1346  Salomon Shoes 129.99 7

我需要的是将id转换为'int'变量。为什么抛出NumberFormatException?

BufferedReader bufferedReader = new BufferedReader(new FileReader("d:\\temp\\prices.txt"));

String line = bufferedReader.readLine();
String id = line.split(" ")[0];
int result = Integer.parseInt(id);
System.out.println(result + 1);

但是当我使用consoleReader

时,它不会抛出NumberFormatException
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

并输入完全相同的行!?

1 个答案:

答案 0 :(得分:0)

BufferedReader bufferedReader;
String line = null;

try {
    bufferedReader = new BufferedReader(new FileReader(
            "prices.txt"));
    line = bufferedReader.readLine();
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
String id[] = line.split(" ");

int result = Integer.parseInt(id[0]);
System.out.println(result + 1);