폴더가 있는지 확인하는 방법
새로운 Java 7 IO 기능을 조금 사용하고 있습니다.사실 저는 폴더에 있는 모든 XML 파일을 가져오려고 합니다.그러나 폴더가 존재하지 않으면 예외가 발생합니다.새 IO를 사용하여 폴더가 존재하는지 확인하려면 어떻게 해야 합니까?
public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
사용.java.nio.file.Files
:
Path path = ...;
if (Files.exists(path)) {
// ...
}
이 메서드는 옵션으로 패스할 수 있습니다.LinkOption
값:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
또 다른 방법이 있습니다.notExists
:
if (Files.notExists(path)) {
매우 간단합니다.
new File("/Path/To/File/or/Directory").exists();
또, 디렉토리인 것을 확인하고 싶은 경우:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
새 IO를 가진 디렉토리가 있는지 확인하려면:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory
돌아온다true
파일이 디렉토리인 경우false
파일이 존재하지 않거나 디렉토리가 아닌 경우 또는 파일이 디렉토리인지 여부를 확인할 수 없습니다.
메뉴얼을 참조해 주세요.
폴더 디렉토리의 문자열에서 파일 생성
String path="Folder directory";
File file = new File(path);
사용 방법이 존재합니다.
폴더를 생성하려면 mkdir()를 사용해야 합니다.
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
경로(Path)를File
존재 여부 테스트:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
따로 전화할 필요는 없습니다.exists()
메서드(as)isDirectory()
는 디렉토리의 존재 여부를 암묵적으로 체크합니다.
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
파일 및 폴더를 확인할 수 있습니다.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
SonarLint에서 경로를 이미 가지고 있는 경우path.toFile().exists()
대신Files.exists
퍼포먼스를 향상시킵니다.
그
Files.exists
메서드는 JDK 8의 성능이 현저히 떨어지며 실제로 존재하지 않는 파일을 확인하는 데 사용할 경우 응용 프로그램의 속도가 크게 느려질 수 있습니다.
에 대해서도 마찬가지다.Files.notExists
,Files.isDirectory
그리고.Files.isRegularFile
.
비준수 코드 예시:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
준거 솔루션:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}
언급URL : https://stackoverflow.com/questions/15571496/how-to-check-if-a-folder-exists
'itsource' 카테고리의 다른 글
MacOS에서 MariaDB 10.4의 루트 비밀번호를 설정하는 방법 (0) | 2022.11.04 |
---|---|
log4j.properties 파일에서 log4j.rootLogger 속성의 중요성은 무엇입니까?이 부동산을 사용하지 않으면 어떻게 됩니까? (0) | 2022.11.04 |
JetBrains 웹IDE: PHP 변수 유형 힌트입니까? (0) | 2022.11.04 |
MySQL에서 타임스탬프 날짜를 날짜 전용 매개 변수와 비교하는 방법 (0) | 2022.11.04 |
조직에 속한 모든 사용자를 가져오기 위한 MySQL 쿼리 (0) | 2022.11.04 |