简体   繁体   English

Java中是否存在文件?

[英]File Exists in Java?

I trying to check whether a file exists at given directory location. 我试图检查在给定目录位置是否存在文件。

File seacrhFile = new File("D:/input", contract.conf);
if (seacrhFile.exists()) {
  returnFile = seacrhFile;
} else {
  System.out.println("No such file exists");
}
reutrn returnFile;

This is working in D:/input directory scenario, but if I Change the directory location to src/test/resources/input folder then I am getting No such file exists , eventhough the file exists. 这在D:/input目录方案中有效,但是如果我将目录位置更改为src/test/resources/input文件夹,那么即使No such file exists ,我也No such file exists

If you want to have access to 如果您想访问
src/test/resources/input src /测试/资源/输入
you probably should use 你可能应该使用

System.getProperty("user.dir") + File.separator + "src/test/resources/input"

because the system-property "user.dir" points to the projectlocation. 因为系统属性“ user.dir”指向项目位置。

If you just use "src/test/resources/input" you will get your mentioned exception, because the File Object don't "start" at the project location. 如果仅使用“ src / test / resources / input”,则会得到您提到的异常,因为File Object不会在项目位置“启动”。 So you have to specify it manually. 因此,您必须手动指定它。

Nevertheless it's better to use the getResource-Method to retrieve different resources within your project, because if you run your project with the jar-File you need to tweak around to get "user.dir" to work correctly. 不过,最好使用getResource-Method来检索项目中的不同资源,因为如果使用jar-File运行项目,则需要进行调整以使“ user.dir”正常工作。

Just a basic example for the Classloader: 只是类加载器的一个基本示例:

ClassLoader.getSystemClassLoader().getResource("test/resources/input");

This returns an URL-Object, with this object you can get the File-Object using ... 这将返回一个URL对象,使用此对象,您可以使用...获取文件对象。

URL filePath =  ClassLoader.getSystemClassLoader().getResource("test/resources/input");
File file = new File( filePath.toURI() );

删除src,然后重试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM