我到达这里NullPointerException。如何解决呢?

时间:2019-05-24 15:04:31

标签: java exception nullpointerexception

为什么在Junit测试中会出现NullPointerException?我可以使用扫描仪使此代码更容易,但是由于声纳,我无法做到这一点。

public void readList() throws IOException {
        final List<Integer> list = new ArrayList<>();
        BufferedReader out = null;
        final URL url = this.getClass().getResource("numbers.txt");
        final File file = new File(url.getPath());

尝试阻止

        try (FileInputStream fis = new FileInputStream(file);
                Reader br = new InputStreamReader(fis, "UTF-8");
                BufferedReader reader = new BufferedReader(br)) {

            out = reader;

            String text = null;

            while ((text = reader.readLine()) != null) {
                list.add(Integer.parseInt(text));
            }

            for (final Integer num : list) {
                ListOfNumbers.LOGGER.info("{}", num);
                ListOfNumbers.LOGGER.info("{}", ' ');

            }

我在这里遇到了一些例外情况

        } catch (final FileNotFoundException e) {

            ListOfNumbers.LOGGER.info("{}", "FileNotFoundException: " + e.getMessage());
            ListOfNumbers.LOGGER.info("{}", e);
        } catch (final IOException e) {

            ListOfNumbers.LOGGER.info("{}", "IOException: " + e.getMessage());
            ListOfNumbers.LOGGER.info("{}", e);
        } finally {
            if (out == null) {

                ListOfNumbers.LOGGER.info("{}", "PrintReader not open");

            } else {
                ListOfNumbers.LOGGER.info("{}", "Closing PrintReader");
                out.close();
            }
        }

    }

1 个答案:

答案 0 :(得分:2)

如果找不到具有该名称的资源,则

Class.getResource(String name)返回null。您可能需要检查资源在类路径中的哪个位置并使用它。 例如,如果资源位于src/main/resources中,则可以尝试:

final URL url = this.getClass().getResource("/numbers.txt");

请注意名称前的/

以下是文档:https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-