createNewFile()导致警告消息,如何消除?

Kad*_*NEL 7 java warnings file

通过使用类的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.


}
Run Code Online (Sandbox Code Playgroud)

警告是:

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

谢谢

Ser*_*kyy 10

如果要避免这些消息,则可以在这些方法返回false时为该案例提供日志记录.

像这样的东西

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


omu*_*gru 6

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

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
}
Run Code Online (Sandbox Code Playgroud)