任务是读取 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))) {
...
}
...
}
}
...
}
}
这个问题在这里讨论:https ://ru.stackoverflow.com/questions/549386/Where-should-the-file-for-getclassloader-getresourceasstream/549400
您只需将 Ex8 类所在文件夹的名称放在文件名之前。那些。如果是“ex8”文件夹,则:
如果呼叫来自上一层的文件夹。
如果您不使用 Maven 或 Gradle,上述解决方案将真正起作用。例如,如果您使用 Maven,则文件应沿路径放置
src/main/resources