【问题标题】:fix Possible null pointer dereference修复可能的空指针取消引用
【发布时间】:2018-06-25 21:24:14
【问题描述】:

我有以下代码,但在使用 findbugs 时失败。

    protected void writeStream(final InputStream inputStream, final Path destinationFile) throws IOException {
    final Path parentDirectory = destinationFile.getParent();
    Path tempFile = null;
    try {
        // Create the temporary dir for temporary download
        Files.createDirectories(getTempDownloadPath());
        Files.createDirectories(parentDirectory);
        // Create the temporary file in the temporary dir
        tempFile = Files.createTempFile(getTempDownloadPath(), destinationFile.getFileName().toString(), ".tmp");
        long t1 = System.currentTimeMillis();
        Files.copy(inputStream, tempFile, REPLACE_EXISTING);
        long t2 = System.currentTimeMillis();
        Files.move(tempFile, destinationFile, ATOMIC_MOVE, REPLACE_EXISTING);
        long t3 = System.currentTimeMillis();
    } catch (final IOException e) {
        log.error("Failed to write file.", e);
        throw e;
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (tempFile != null) {
                Files.deleteIfExists(tempFile);
            }
        } catch (IOException e) {
            log.warn("Failed to delete file: " + tempFile, e);
        }
    }
}

这是在抱怨

tempFile = Files.createTempFile(getTempDownloadPath(), destinationFile.getFileName().toString(), ".tmp");

由于被调用方法的返回值可能导致空指针取消引用

哪一部分出了问题,我该如何解决?

【问题讨论】:

  • PathgetFileName()方法可以返回null。
  • 即使我在一开始就添加了一个特定的检查来检查destinationFile!=null,它仍然失败。
  • 但他不是这么说的。
  • 可能是因为destinationFile不为null,但是destinationFile.getFileName()可以返回null并且你调用toString()就可以了
  • 完整的错误信息是什么?

标签: java findbugs


【解决方案1】:

Files.createTempFile 不返回 Path 对象,而是一个字符串。

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2017-02-12
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多