任务是读取 WordsEx7.txt 文件,该文件与 Ex8 类位于同一文件夹中。初始化扫描器,以便我们从类路径中获取文件。从这里尝试的选项 https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar https://stackoverflow.com/questions/1464291/how-to-really-read-text -file-from-classpath-in-java
结果是一样的:in = null 和 NullPointerException。我试图更改文件的位置并将其作为参数传递(“/wordsEx7.txt”)。它也没有帮助。
public class Ex8 {
public static void main(String... args) throws IOException {
Map<String,Set<Integer>> words = new HashMap<>();
InputStream in = Ex8.class.getClassLoader().getResourceAsStream("wordsEx7.txt");
try(Scanner scanner = new Scanner(new InputStreamReader(in))) {
...
}
...
}
}
...
}
}