修复可能的空指针取消引用

问题描述 投票:-3回答:1

我有以下代码但使用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");

由于被调用方法的返回值而可能出现空指针取消引用

哪部分是错的,我该如何解决?

java findbugs
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.