有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

当我运行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) 个答案

  1. # 1 楼答案

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

    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

    它正在读取文件的结尾并返回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(""));