How can I check whether a file exists, before opening it for reading in Java? (equivalent of Perl's -e $filename
).
如何在打开文件以供Java阅读之前检查文件是否存在?(相当于Perl的-e $文件名)。
The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.
唯一类似的问题是写文件,因此使用FileWriter回答,显然在这里是不适用的。
If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in text", but I can live with the latter.
如果可能的话,我更希望一个真正的API调用返回true/false,而不是“调用API来打开一个文件并捕获它抛出的异常,您可以在文本中检查‘no file’”,但是我可以接受后者。
20 个解决方案
#1
1132
Using java.io.File
:
使用java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
#2
373
I would recommend using isFile()
instead of exists()
. Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists()
will return true if your path points to a directory.
我建议使用isFile()而不是exist()。大多数情况下,您要检查路径是否指向文件,而不仅仅是文件是否存在。请记住,如果您的路径指向一个目录,那么exist()将返回true。
new File("path/to/file.txt").isFile();
new File("C:/").exists()
will return true but will not allow you to open and read from it as a file.
新文件(“C:/”).exist()将返回true,但不允许您将其作为文件打开并读取。
#3
118
By using nio in Java SE 7,
在Java SE 7中使用nio,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)
如果存在且不存在返回false,则无法验证该文件的存在。(可能没有访问路径的权限)
You can check if path is directory or regular file.
您可以检查路径是目录还是常规文件。
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Please check this Java SE 7 tutorial.
请参阅本Java SE 7教程。
#4
31
Using Java 8:
使用Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}
#5
26
File f = new File(filePathString);
This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:
这不会创建物理文件。将只创建类文件的对象。要物理地创建一个文件,您必须显式地创建它:
f.createNewFile();
So f.exists()
can be used to check whether such a file exists or not.
因此,可以使用f.exists()检查此类文件是否存在。
#6
24
f.isFile() && f.canRead()
#7
15
first hit for "java file exists" on google:
谷歌上“java文件存在”的第一次点击:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
#8
14
You can use the following: File.exists()
您可以使用以下内容:File.exists()
#9
10
Don't. Just catch the FileNotFoundException.
The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:
不喜欢。只是抓住FileNotFoundException。文件系统必须测试文件是否存在。做这两件事没有意义,有几个理由不这样做,比如:
- double the code
- 代码的两倍
- the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
- 计时窗口问题,当您测试时文件可能存在,但当您打开时却不存在,反之亦然
- the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.
- 事实是,正如这个问题的存在所表明的,你可能做了错误的测试并得到了错误的答案。
Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.
不要试图去猜测这个系统。它知道。不要试图预测未来。一般来说,测试任何资源是否可用的最佳方法就是尝试使用它。
#10
8
For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.
对我来说,Sean A.O. Harney的公认答案和Cort3z的评论结合起来似乎是最好的解决方案。
Used the following snippet:
使用以下代码片段:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Hope this could help someone.
希望这能帮助到别人。
#11
6
There are multiple ways to achieve this.
有多种方法可以实现这一点。
-
In case of just for existence. It could be file or a directory.
如果只是为了生存。它可以是文件或目录。
new File("/path/to/file").exists();
-
Check for file
检查文件
File f = new File("/path/to/file"); if(f.exists() && f.isFile()) {}
-
Check for Directory.
检查目录。
File f = new File("/path/to/file"); if(f.exists() && f.isDirectory()) {}
-
Java 7 way.
Java 7的方法。
Path path = Paths.get("/path/to/file"); Files.exists(path) // Existence Files.isDirectory(path) // is Directory Files.isRegularFile(path) // Regular file Files.isSymbolicLink(path) // Symbolic Link
#12
4
It's also well worth getting familiar with Commons FileUtils http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html This has additional methods for managing files and often better than JDK.
同样值得熟悉的还有Commons FileUtils http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html,它有管理文件的附加方法,而且通常比JDK更好。
#13
2
I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.
我知道我有点迟了。但是,这里是我的答案,因为Java 7和更高版本有效。
The following snippet
以下代码片段
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
is perfectly satifactory, because method isRegularFile
returns false
if file does not exist. Therefore, no need to check if Files.exists(...)
.
因为如果文件不存在,方法isRegularFile会返回false。因此,不需要检查文件是否存在。
Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.
注意,其他参数是指示如何处理链接的选项。默认情况下,遵循符号链接。
From Java Oracle documentation
从Java甲骨文文档
#14
1
If you want to check for a File
in a directory dir
String directoryPath = dir.getAbsolutePath()
boolean check = new File(new File(directoryPath), aFile.getName()).exists();
and check the check
result
并检查检查结果
#15
1
new File("/path/to/file").exists();
will do the trick
会做的技巧
#16
1
Don't use File constructor with String.
This may not work!
Instead of this use URI:
不要使用带有字符串的文件构造函数。这可能不是工作!而不是使用URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
#17
1
File.exists()
to check if a file exists, it will return a boolean value to indicate the check operation status; true if the file is existed; false if not exist.
exist()为了检查文件是否存在,它将返回一个布尔值来指示检查操作状态;如果该文件存在,则为;如果不存在错误。
File f = new File("c:\\test.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
#18
1
For example if you have a file directory and you want to check if it exists
例如,如果你有一个文件目录,你想检查它是否存在
File tmpDir = new File("/var/tmp");
boolean exists = tmpDir.exists();
exists
will return false if the file doesn't exist
如果文件不存在,则exist将返回false
source: https://alvinalexander.com/java/java-file-exists-directory-exists
来源:https://alvinalexander.com/java/java-file-exists-directory-exists
#19
0
You can use the following code to check:
您可以使用以下代码进行检查:
import java.io.File;
class Test{
public static void main(String[] args){
File f = new File(args[0]); //file name will be entered by user at runtime
System.out.println(f.exists()); //will print "true" if the file name given by user exists, false otherwise
if(f.exists())
{
//executable code;
}
}
}
#20
-2
To check if a file exists, just import the java.io.* library
要检查文件是否存在,只需导入java.io。*库
File f = new File(“C:\\File Path”);
if(f.exists()){
System.out.println(“Exists”); //if file exists
}else{
System.out.println(“Doesn't exist”); //if file doesn't exist
}
Source: http://newsdivariotipo.altervista.org/java-come-controllare-se-un-file-esiste/
来源:http://newsdivariotipo.altervista.org/java-come-controllare-se-un-file-esiste/
#1
1132
Using java.io.File
:
使用java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
#2
373
I would recommend using isFile()
instead of exists()
. Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists()
will return true if your path points to a directory.
我建议使用isFile()而不是exist()。大多数情况下,您要检查路径是否指向文件,而不仅仅是文件是否存在。请记住,如果您的路径指向一个目录,那么exist()将返回true。
new File("path/to/file.txt").isFile();
new File("C:/").exists()
will return true but will not allow you to open and read from it as a file.
新文件(“C:/”).exist()将返回true,但不允许您将其作为文件打开并读取。
#3
118
By using nio in Java SE 7,
在Java SE 7中使用nio,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)
如果存在且不存在返回false,则无法验证该文件的存在。(可能没有访问路径的权限)
You can check if path is directory or regular file.
您可以检查路径是目录还是常规文件。
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Please check this Java SE 7 tutorial.
请参阅本Java SE 7教程。
#4
31
Using Java 8:
使用Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}
#5
26
File f = new File(filePathString);
This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:
这不会创建物理文件。将只创建类文件的对象。要物理地创建一个文件,您必须显式地创建它:
f.createNewFile();
So f.exists()
can be used to check whether such a file exists or not.
因此,可以使用f.exists()检查此类文件是否存在。
#6
24
f.isFile() && f.canRead()
#7
15
first hit for "java file exists" on google:
谷歌上“java文件存在”的第一次点击:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
#8
14
You can use the following: File.exists()
您可以使用以下内容:File.exists()
#9
10
Don't. Just catch the FileNotFoundException.
The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:
不喜欢。只是抓住FileNotFoundException。文件系统必须测试文件是否存在。做这两件事没有意义,有几个理由不这样做,比如:
- double the code
- 代码的两倍
- the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
- 计时窗口问题,当您测试时文件可能存在,但当您打开时却不存在,反之亦然
- the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.
- 事实是,正如这个问题的存在所表明的,你可能做了错误的测试并得到了错误的答案。
Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.
不要试图去猜测这个系统。它知道。不要试图预测未来。一般来说,测试任何资源是否可用的最佳方法就是尝试使用它。
#10
8
For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.
对我来说,Sean A.O. Harney的公认答案和Cort3z的评论结合起来似乎是最好的解决方案。
Used the following snippet:
使用以下代码片段:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Hope this could help someone.
希望这能帮助到别人。
#11
6
There are multiple ways to achieve this.
有多种方法可以实现这一点。
-
In case of just for existence. It could be file or a directory.
如果只是为了生存。它可以是文件或目录。
new File("/path/to/file").exists();
-
Check for file
检查文件
File f = new File("/path/to/file"); if(f.exists() && f.isFile()) {}
-
Check for Directory.
检查目录。
File f = new File("/path/to/file"); if(f.exists() && f.isDirectory()) {}
-
Java 7 way.
Java 7的方法。
Path path = Paths.get("/path/to/file"); Files.exists(path) // Existence Files.isDirectory(path) // is Directory Files.isRegularFile(path) // Regular file Files.isSymbolicLink(path) // Symbolic Link
#12
4
It's also well worth getting familiar with Commons FileUtils http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html This has additional methods for managing files and often better than JDK.
同样值得熟悉的还有Commons FileUtils http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html,它有管理文件的附加方法,而且通常比JDK更好。
#13
2
I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.
我知道我有点迟了。但是,这里是我的答案,因为Java 7和更高版本有效。
The following snippet
以下代码片段
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
is perfectly satifactory, because method isRegularFile
returns false
if file does not exist. Therefore, no need to check if Files.exists(...)
.
因为如果文件不存在,方法isRegularFile会返回false。因此,不需要检查文件是否存在。
Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.
注意,其他参数是指示如何处理链接的选项。默认情况下,遵循符号链接。
From Java Oracle documentation
从Java甲骨文文档
#14
1
If you want to check for a File
in a directory dir
String directoryPath = dir.getAbsolutePath()
boolean check = new File(new File(directoryPath), aFile.getName()).exists();
and check the check
result
并检查检查结果
#15
1
new File("/path/to/file").exists();
will do the trick
会做的技巧
#16
1
Don't use File constructor with String.
This may not work!
Instead of this use URI:
不要使用带有字符串的文件构造函数。这可能不是工作!而不是使用URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
#17
1
File.exists()
to check if a file exists, it will return a boolean value to indicate the check operation status; true if the file is existed; false if not exist.
exist()为了检查文件是否存在,它将返回一个布尔值来指示检查操作状态;如果该文件存在,则为;如果不存在错误。
File f = new File("c:\\test.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
#18
1
For example if you have a file directory and you want to check if it exists
例如,如果你有一个文件目录,你想检查它是否存在
File tmpDir = new File("/var/tmp");
boolean exists = tmpDir.exists();
exists
will return false if the file doesn't exist
如果文件不存在,则exist将返回false
source: https://alvinalexander.com/java/java-file-exists-directory-exists
来源:https://alvinalexander.com/java/java-file-exists-directory-exists
#19
0
You can use the following code to check:
您可以使用以下代码进行检查:
import java.io.File;
class Test{
public static void main(String[] args){
File f = new File(args[0]); //file name will be entered by user at runtime
System.out.println(f.exists()); //will print "true" if the file name given by user exists, false otherwise
if(f.exists())
{
//executable code;
}
}
}
#20
-2
To check if a file exists, just import the java.io.* library
要检查文件是否存在,只需导入java.io。*库
File f = new File(“C:\\File Path”);
if(f.exists()){
System.out.println(“Exists”); //if file exists
}else{
System.out.println(“Doesn't exist”); //if file doesn't exist
}
Source: http://newsdivariotipo.altervista.org/java-come-controllare-se-un-file-esiste/
来源:http://newsdivariotipo.altervista.org/java-come-controllare-se-un-file-esiste/