Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查Java文件是否存在_Java_File_Exists - Fatal编程技术网

检查Java文件是否存在

检查Java文件是否存在,java,file,exists,Java,File,Exists,我正在检查Hashmap文件是否存在。该文件在Eclipse中创建并显示在我的默认包中。如果它存在,我将在hashmap中读取,如果不存在,我将创建一个新文件。由于某些原因,代码当前没有看到创建的文件 public UrlCache() throws UrlCacheException { File hmFile = new File(System.getProperty("user.dir") + "\\hashMapFile.properties"); System.out.

我正在检查Hashmap文件是否存在。该文件在Eclipse中创建并显示在我的默认包中。如果它存在,我将在hashmap中读取,如果不存在,我将创建一个新文件。由于某些原因,代码当前没有看到创建的文件

public UrlCache() throws UrlCacheException {
    File hmFile = new File(System.getProperty("user.dir") + "\\hashMapFile.properties");
    System.out.println("Working Directory = "+ hmFile);


    if(hmFile.exists()) { 
        System.out.println("File Exists");
    }
    else{
    System.out.println("File does not exist");
    }
}

您不需要使用exists()方法显式检查文件是否存在createNewFile()方法即可

createNewFile()将创建一个不存在的新文件并返回true,但如果该文件存在,createNewFile()将返回false

File f = new File(System.getProperty("user.dir") + "\\hashMapFile.properties");
if(f.createNewFile()) {
   System.out.println("Created new Hashmap file");
}

我们没有在这里编写else部分,因为根据您提到的要求,没有必要这样做。

我想您在Eclipse中的
默认包与
System.getProperty(“user.dir”)
2问题不同。它似乎需要f.createNewFile()的IOException,如果我添加了它,它还需要在主类中抛出它。第二个问题是它根本不起作用。未创建任何文件。在使用IO时,您需要处理一些异常以处理负面场景。对于第二个问题,您应该查找尝试保存hashMapFile.properties文件的路径。可能是错误的,只需尝试传递一些硬编码路径,如file f=new file(“/home/local/naresh.j”+“/hashMapFile.properties”)