Java에 파일이 있는지 어떻게 확인합니까?
Java에서 읽기 위해 파일을 열기 전에 파일이 존재하는지 어떻게 확인할 수 있습니까? (Perl과 동일 -e $filename
).
SO에 대한 유일한 유사한 질문 은 파일 작성과 관련이 있으므로 FileWriter를 사용하여 대답했으며 여기에는 분명히 적용 할 수 없습니다.
가능한 경우 일부 "파일을 열고 텍스트에서 '파일 없음'을 확인하는 예외가 발생할 때 catch하는 API 호출"과는 반대로 true / false를 반환하는 실제 API 호출을 선호하지만, 후자.
사용 java.io.File
:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
isFile()
대신 사용 하는 것이 좋습니다 exists()
. 대부분의 경우 경로가 파일이 존재하는지뿐만 아니라 파일을 가리키는 지 확인하려고합니다. 그 기억 exists()
의 디렉토리 경로 점의 경우 true를 돌려줍니다.
new File("path/to/file.txt").isFile();
new File("C:/").exists()
true를 반환하지만 파일로 열고 읽을 수는 없습니다.
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
}
두 경우 exists
와 notExists
반환 허위, 파일의 존재는 확인할 수 없습니다. (이 경로에 대한 액세스 권한이 없을 수도 있음)
path
디렉토리 또는 일반 파일인지 확인할 수 있습니다 .
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
이 Java SE 7 자습서를 확인하십시오 .
Java 8 사용 :
if(Files.exists(Paths.get(filePathString))) {
// do something
}
File f = new File(filePathString);
이것은 실제 파일을 생성하지 않습니다. File 클래스의 객체를 생성합니다. 파일을 물리적으로 생성하려면 명시 적으로 생성해야합니다.
f.createNewFile();
따라서 f.exists()
이러한 파일이 있는지 여부를 확인하는 데 사용할 수 있습니다.
f.isFile() && f.canRead()
이를 달성하는 방법에는 여러 가지가 있습니다.
그냥 존재하는 경우. 파일 또는 디렉토리 일 수 있습니다.
new File("/path/to/file").exists();
파일 확인
File f = new File("/path/to/file"); if(f.exists() && f.isFile()) {}
디렉토리를 확인하십시오.
File f = new File("/path/to/file"); if(f.exists() && f.isDirectory()) {}
자바 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
다음을 사용할 수 있습니다. File.exists()
구글에서 "자바 파일 존재"에 대한 첫 번째 히트 :
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 "));
}
}
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:
- 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.
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.
Used the following snippet:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Hope this could help someone.
I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.
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(...)
.
Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.
From Java Oracle documentation
It's also well worth getting familiar with Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html This has additional methods for managing files and often better than JDK.
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
source: https://alvinalexander.com/java/java-file-exists-directory-exists
Simple example with good coding practices and covering all cases :
private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
if (f.exists()) {
throw new FileAlreadyExistsException(f.getAbsolutePath());
} else {
try {
URL u = new URL(url);
FileUtils.copyURLToFile(u, f);
} catch (MalformedURLException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Reference and more examples at
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations
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
new File("/path/to/file").exists();
will do the trick
Don't use File constructor with String.
This may not work!
Instead of this use URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
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.
File f = new File("c:\\test.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
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;
}
}
}
You can make it this way
import java.nio.file.Paths;
String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
//...do somethinh
}
There is specific purpose to design these methods. We can't say use anyone to check file exist or not.
- isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
- exists(): Tests whether the file or directory denoted by this abstract pathname exists. docs.oracle.com
To check if a file exists, just import the java.io.* library
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/
참고URL : https://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-in-java
'program tip' 카테고리의 다른 글
Docker 컨테이너에 환경 변수를 전달하려면 어떻게해야합니까? (0) | 2020.09.30 |
---|---|
자바 스크립트가 변수로 개체 키 설정 (0) | 2020.09.29 |
문자를 문자열로 변환하는 방법? (0) | 2020.09.29 |
.First를 언제 사용하고 .FirstOrDefault를 LINQ와 함께 사용합니까? (0) | 2020.09.29 |
중첩 된 객체, 배열 또는 JSON에 액세스하고 처리하려면 어떻게해야합니까? (0) | 2020.09.29 |