【问题标题】:createNewFile( ) causes warning message, how to eliminate?createNewFile( ) 导致警告信息,如何消除?
【发布时间】:2014-08-07 06:05:04
【问题描述】:

通过使用createNewFile 方法和File 类的删除方法,我成功地从我的程序中生成了文件。但是在编译过程之后会有一条恼人的警告信息。我的问题是如何在不使用@SUPPRESSWARNIGN 的情况下删除该警告消息。因为当我检查我的代码时,我看到了由这两种方法引起的可能的错误警告。是的,通过使用@SuppressWarning 警告和可能的错误消息消失。

我不知道它是否与Java版本有关,但无论如何我使用的是Java 8。我针对这个问题进行了研究,在互联网上找不到任何东西。我看到互联网上的人们以与我相同的方式使用这两种方法。可能是他们忽略了警告信息。但我不想。

这是我的代码:

private void createAFile() throws IOException {

    String outputFileName = getFileName();
    String outputPathName = getFilePath();
    String fullOutputPath = outputPathName + "/" + outputFileName;

    output = new File(fullOutputPath);

    if(output.exists()){

        output.delete(); //this returns a boolean variable.

    }

    output.createNewFile(); //this also return a boolean variable.


}

警告是:

警告:(79, 20) 'File.delete()' 的结果被忽略。 警告:(84, 16) 'File.createNewFile()' 的结果被忽略。

谢谢

【问题讨论】:

  • 如果你说什么这些警告是真的会有帮助。
  • 我在 Java 8 中看不到该代码的任何警告。
  • 警告:(79, 20) 'File.delete()' 的结果被忽略。并且警告:(84, 16) 'File.createNewFile()' 的结果被忽略

标签: java file warnings


【解决方案1】:

这些看起来像是从代码检查工具生成的警告。我要做的是:

boolean deleted,created; // both should be instantiatd to false by default
if(output.exists()){

   deleted = output.delete(); //this returns a boolean variable.
} 
if(deleted){ 
    created = output.createNewFile();
}
if(!deleted||!created){
    // log some type of warning here or even throw an exception
}

【讨论】:

  • 谢谢 :) 由于我是 Stackoverflow 的新手,我无法投票赞成您的答案。但我“抽象地”投票赞成你的答案。
【解决方案2】:

如果您想避免这些消息,您可以为这些方法返回 false 的情况提供日志记录。

类似的东西

private static Logger LOG = Logger.getLogger("myClassName");
// some code
if (!output.delete()) {
  LOG.info("Cannot delete file: " + output);
}

【讨论】:

  • 感谢您的日志想法 :) 目前无法投票,对此感到抱歉。
猜你喜欢
  • 2017-06-11
  • 1970-01-01
  • 2021-01-16
  • 2010-12-17
  • 1970-01-01
  • 2016-01-25
  • 2015-06-28
  • 2014-01-18
  • 1970-01-01
相关资源
最近更新 更多