Java.util.Scanner读取器如何允许空指针异常

时间:2015-05-27 02:54:57

标签: java

请告诉我如何允许空数据?

我的输入数据:

4,Get,NULL,,0,2015/05/14 11:06:26,2015/05/14 11:06:28

输出错误:

java.lang.NumberFormatException: For input string: "2015/05/14 11:06:26"

我的代码:

public List<Row> getListFileData() {

     File file = new File(file.txt);

     FileReader fr = new FileReader(file);

     Scanner in = new Scanner(fr);

     while (in.hasNext()) {
  try{
     String line = in.nextLine().replace("\"", ""); // here line like 4,Get,NULL,,0,2015/05/14 11:06:26,2015/05/14 11:06:28

        Scanner lineBreaker = new Scanner(line);

        lineBreaker.useDelimiter(", *");

      String job_id = lineBreaker.next().trim();

      String job_type = lineBreaker.next();

     String job_state = lineBreaker.next().trim();

     String job_process = lineBreaker.next().trim();

    String che_id = lineBreaker.next().trim();

    int job_step =Integer.valueOf(lineBreaker.next().trim()); //here error numberformat excception 

 }catch(NullpointerException ex){
 ex.printStackTrace();
 }



 return list;
   }
}

1 个答案:

答案 0 :(得分:1)

您可以使用错误值sentinel(例如-1),或使用包装器Integer而不是基本类型int(它不能代表null })。另外,我建议您考虑使用String.split(String)try-with-resources close() Scanner {并传入File)。像

这样的东西
public List<Row> getListFileData(File file) {
    List<Row> list = new ArrayList<>();
    try (Scanner in = new Scanner(file)) {
        while (in.hasNextLine()) {
            // here line like
            // 4,Get,NULL,,0,2015/05/14 11:06:26,2015/05/14 11:06:28
            String line = in.nextLine();
            String[] arr = line.split(",");
            String job_id = arr[0].trim();
            String job_type = arr[1].trim();
            String job_state = arr[2].trim();
            String job_process = arr[3].trim();
            String che_id = arr[4].trim();
            // This would appear to be a Date and Time in your sample input...
            Integer job_step = Integer.valueOf(arr[5].trim());
            Row r = new Row();
            // ...
            list.add(r);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return list;
}

如果您确实需要解析上面的日期和时间,我会使用SimpleDateFormat ...我想你想要像

这样的东西
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date job_step = sdf.parse(arr[5].trim());