想要从我的文件中读取唯一编号 |错误 - java.lang.NullPointerException

Want to unique number out of my file read | error - java.lang.NullPointerException

我不确定我是否收到 NullPointerException 异常我是新手 java 任何人都可以帮助解决这个问题。

Code i am using for this -

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;

public class sortNumberOfFile {
    public static void main(String[] args) throws IOException,
            InterruptedException {
        HashSet<String> hs = null;
        String perLine;
        String filename = "C:\Users\dummy\Downloads\ip.txt";
        BufferedReader br = new BufferedReader(new FileReader(filename));

        while ((perLine = br.readLine()) != null) {
            System.out.println("whole line : " + perLine);

            String[] eachLine = perLine.split(",");
            System.out.println("custom element " + eachLine[0] + " "
                    + eachLine[2] + " count " + eachLine.length);

            for (String str : eachLine) {
                System.out.println("Adding "+str);
                //Thread.sleep(2000);
                hs.add(str);
            }

//          Collections.addAll(hs, eachLine);
            System.out.println(hs);

        }
    }

}

控制台输出我得到 -

whole line : 1,2,32,4,5,234,6,12,3,67,3421,123,2,2,34,5,4
custom element 1 32 count 17
Adding 1
Exception in thread "main" java.lang.NullPointerException
    at org.gour.indrajeet.practice.sortNumberOfFile.main(sortNumberOfFile.java:27)

NullPointerException 当应用程序尝试使用具有 null 值的对象引用时抛出。

请注意,您尚未在此处使用 new 创建 HashSet 对象:

HashSet<String> hs = null;

此外,您正在此处调用 null 引用对象的方法:

hs.add(str);

可能是:

HashSet<String> hs = new HashSet<>();

您首先编写 HashSet<String> hs = null;,然后在循环中编写 hs.add(str);。因为 hsnull,你不能调用它的 add() 方法。

相反,声明如下:

HashSet<String> hs = new HashSet<>();