Java 에서 읽기 위해 파일을 열기 전에 파일이 존재하는지 어떻게 확인할 수 있습니까 ( Perl 과 동일
-e $filename)?
SO에 대한 유일한 비슷한 질문 은 파일 작성을 다루므로 FileWriter여기에는 해당되지 않습니다.
가능한 경우 "파일을 열고 텍스트에서 '파일 없음'을 확인하는 예외가 발생하면 catch하는 API 호출과 달리 true / false를 반환 하는 실제 API 호출을 선호 하지만 후자의.
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
}
if(f.isFile())대신 사용하십시오 .
isFile()대신에 사용 하는 것이 좋습니다 exists(). 대부분의 경우 경로가 파일이 아닌 파일을 가리키는 지 확인하려고합니다. 그 기억 exists()의 디렉토리 경로 점의 경우 true를 돌려줍니다.
new File("path/to/file.txt").isFile();
new File("C:/").exists() true를 반환하지만 파일로 열고 읽을 수는 없습니다.
/path, new File("file.txt").exists()반환 true올바른 전체 경로 인 경우 /path/to/file.txt(다른 파일이없는 한, 대답은 큰 아니오는 /path/file.txt존재한다).
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.nio.file.Files.exists()는 (테스트 한 유일한 컴퓨터 : Java 1.7.0_45 x64를 실행하는 Windows Server 2012의 소규모 벤치 마크) 보다 훨씬 빠릅니다 java.io.File.exists().
java.nio.file.Files.exists()5 배 느 렸습니다java.io.File.exists . (Win7 Java 1.7.0_79-x86)
자바 8 :
if(Files.exists(Paths.get(filePathString))) {
// do something
}
Files.exists()두 가지 주장을 취합니다. 일반적으로와 같은 것을 원할 것 Files.exists(path, LinkOption.NOFOLLOW_LINKS )입니다.
이를 달성하기위한 여러 가지 방법이 있습니다.
단지 존재의 경우. 파일 또는 디렉토리 일 수 있습니다.
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 "));
}
}
String.valueOf()null을 처리
하지마 그냥 잡을 FileNotFoundException.파일이 어쨌든 존재하는지 여부를 파일 시스템 테스트에 있습니다. 다음과 같은 두 가지 작업을 수행 할 필요가 없으며 몇 가지 이유가 없습니다.
시스템을 추측하지 마십시오. 알고 있습니다. 미래를 예측하려고하지 마십시오. 일반적으로 여부를 테스트하는 가장 좋은 방법은 어떤 자원을 사용할 수는 단지 그것을 사용하려고하는 것입니다.
이 스레드에서 약간 늦었다는 것을 알고 있습니다. 그러나 여기 내 대답은 Java 7 이상부터 유효합니다.
다음 스 니펫
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
파일이 존재하지 않으면 메서드가 isRegularFile반환 되므로 완벽하게 만족 false합니다. 따라서를 확인할 필요가 없습니다 Files.exists(...).
다른 매개 변수는 링크 처리 방법을 나타내는 옵션입니다. 기본적으로 심볼릭 링크가 따릅니다.
Files.notExists, Files.isDirectory그리고 Files.isRegularFile. 이에 대한 가장 좋은 대안은 다음과 같습니다path.toFile().exists()
또한 가공 Fileutils의에 익숙해지고 잘 가치 https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html 이 파일을 관리하고 추가 방법이있다 종종 JDK보다 낫습니다.
예를 들어 파일 디렉토리가 있고 존재하는지 확인하려는 경우
File tmpDir = new File("/var/tmp");
boolean exists = tmpDir.exists();
exists 파일이 존재하지 않으면 false를 반환합니다
출처 : https://alvinalexander.com/java/java-file-exists-directory-exists
좋은 코딩 관행과 모든 사례를 다루는 간단한 예 :
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);
}
}
}
참조 및 더 많은 예제
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations
File디렉토리에서 를 확인하려면dirString directoryPath = dir.getAbsolutePath()
boolean check = new File(new File(directoryPath), aFile.getName()).exists();
check결과를 확인
new File("/path/to/file").exists();
트릭을 할 것입니다
String과 함께 File 생성자를 사용하지 마십시오.
작동하지 않을 수 있습니다!
이 대신 URI를 사용하십시오.
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
다음 코드를 사용하여 확인할 수 있습니다.
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;
}
}
}
이런 식으로 만들 수 있습니다
import java.nio.file.Paths;
String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
//...do somethinh
}
File.is Exist()또는 Files.isRegularFile()JDK 8
이러한 방법을 설계하는 구체적인 목적이 있습니다. 우리는 파일의 존재 여부를 확인하기 위해 누군가를 사용한다고 말할 수 없습니다.
파일이 존재하는지 확인하려면 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
}
출처 : http://newsdivariotipo.altervista.org/java-come-controllare-se-un-file-esiste/
canRead,canWrite그리고canExecute그 확인하기 위해 .