如何解决空指针异常我的代码?

时间:2017-03-14 03:41:40

标签: java nullpointerexception

当我运行我的java代码时:

public class LalaLuLu {
public static void main(String[] args) {

    try{ 
        String path = "D:/Gem/FINAL/Datatest.csv";
        File file = new File(path);
        InputStream is;
        System.out.println(file.exists());

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        PrintWriter os = new PrintWriter ( new FileOutputStream("D:/Gem/FINAL/out_datatest1.txt"));
        String output = "";
        int count = 0;
        do{
            output = br.readLine();
            String[] a = output.split(";");
            System.out.println("total kolom: " + a.length);
            os.println(output);
            System.out.println(count++ );
        } while (!output.equals(""));

    } catch (Exception e) {
        e.printStackTrace();
    }
} }

当我跑步时,此行上的错误:

output = br.readLine();
String[] a = output.split(";");

我得到的错误是:

java.lang.NullPointerException
  at DAO.readdata.readdataCSV(readdata.java:47)

你能告诉我如何解决这个错误吗?谢谢

1 个答案:

答案 0 :(得分:0)

查看文档了解readLine()的工作原理:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

  

包含该行内容的String,而不是   包括任何行终止字符,如果结尾则为null   流已经到达

正在读取文件的末尾并返回null

最简单的解决方法是以下

 do{
     output = br.readLine();
     if (output == null ) {
         break;
     }
     String[] a = output.split(";");
     System.out.println("total kolom: " + a.length);
     os.println(output);
     System.out.println(count++ );
 } while (!output.equals(""));