Java에서 디렉터리를 만드는 방법?
디렉토리/폴더를 만드는 방법
일단 테스트해 보면System.getProperty("user.home");
새로운 폴더가 없는 경우에만 디렉토리(디렉토리 이름 "새 폴더" )를 작성해야 한다.
new File("/path/directory").mkdirs();
여기서 "디렉토리"는 작성/존재할 디렉터리의 이름이다.
~ 7년 후에 보즈호가 제안하는 더 나은 접근방식으로 업데이트하겠다.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
Java 7에서는 를 사용할 수 있다.
예를 들어,
Files.createDirectories(Paths.get("/path/to/directory"));
FileUtils#forceMkdir을 사용해 보십시오.
FileUtils.forceMkdir("/path/directory");
이 도서관은 많은 유용한 기능을 가지고 있다.
mkdir 대 mkdirs.
단일 디렉토리 사용을 생성하려면mkdir
new File("/path/directory").mkdir();
폴더 구조 사용 계층을 생성하려면mkdirs
new File("/path/directory").mkdirs();
단일 디렉터리를 만드십시오.
new File("C:\\Directory1").mkdir();
"Directory2"라는 디렉토리와 모든 하위 디렉토리 "Sub2" 및 "Sub-Sub2"를 함께 만드십시오.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
출처: 이 완벽한 자습서 , 사용의 예도 찾을 수 있다.
Java 7 이상의 경우:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
디렉터리를 만들기 전에 dir 또는 파일의 존재 여부를 확인할 필요가 없어짐:
존재하지 않는 모든 상위 디렉터리를 먼저 생성하여 디렉터리를 생성하십시오.createDirectory 방식과 달리 디렉터리가 이미 존재하기 때문에 만들 수 없는 경우에는 예외가 발생하지 않는다.특성 매개변수는 존재하지 않는 디렉토리를 작성할 때 원자적으로 설정하는 선택적 파일 특성이다.각 파일 속성은 이름으로 식별된다.배열에 같은 이름의 속성이 둘 이상 포함된 경우 마지막 항목을 제외한 모든 속성이 무시된다.
이 방법이 실패하면 상위 디렉토리의 일부(전부는 아님)를 만든 후 이 방법을 사용할 수 있다.
다음 방법은 원하는 대로 해야 하며, mkdir() / mkdirs()의 반환 값을 확인하고 있는지 확인하십시오.
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
자바에 디렉토리/폴더를 만들기 위해 우리는 두 가지 방법을 가지고 있다.
여기서 medirectory 방법은 존재하지 않는 단일 디렉토리를 만든다.
File dir = new File("path name");
boolean isCreated = dir.mkdir();
그리고
File dir = new File("path name");
boolean isCreated = dir.mkdirs();
여기서 makediceries 메소드는 파일 개체가 나타내는 경로에 누락된 모든 디렉토리를 생성한다.
예를 들어 아래 링크를 참조하십시오(매우 잘 설명됨).도움이 되길 바래!!https://www.flowerbrackets.com/how-to-create-directory-java/
깔끔하고 깨끗함:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
비록 이 질문에 대한 답은 있었지만.나는 당신이 만들려는 디렉토리 이름을 가진 파일이 있는 경우 오류를 발생시킬 수 있는 파일보다 더 많은 것을 추가하고자 한다.미래의 방문객을 위해.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
전화하는 모든 사람들에게File.mkdir()
또는File.mkdirs()
를 File
오브젝트는 파일이 아닌 디렉토리 입니다.예를 들어, 만약 당신이 전화할 경우mkdirs()
진로를 위하여/dir1/dir2/file.txt
, 그것은 이름을 가진 폴더를 만들 것이다.file.txt
그건 아마 네가 원했던 게 아닐 거야새 파일을 만들 때 부모 폴더도 자동으로 만들려면 다음과 같은 작업을 수행하십시오.
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
이런 방식으로 나는 단일 디렉토리 또는 그 이상을 한다: java.io를 가져올 필요가 있다.파일;
/*아래 코드를 입력하여 diectory dir1을 추가하거나 dir1이 존재하는지 여부를 확인하여 dir2 및 dir3 */와 동일하게 생성하십시오.
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
생성 여부를 확인하려면 다음 절차를 따르십시오.
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
비취로 하다mkDir()
부울을 반환하고, 변수를 사용하지 않으면 findbugs가 부울을 부르짖을 것이다.또한 좋지 않다...
mkDir()
의 경우에만 참으로 반환하다.mkDir()
그것을 창조하다.dir이 존재하면 false를 반환하므로, 당신이 만든 dir를 확인하려면, 단지 전화만 하십시오.exists()
만일mkDir()
거짓으로 돌려주다
assertThat()
결과를 확인하고 다음과 같은 경우 실패함exists()
할 수 처리되지 않은 디렉토리를 처리하기 위해 다른 것을 사용할 수 있다.
이 기능을 통해 사용자 홈 디렉토리에 디렉토리를 만들 수 있다.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
참조URL: https://stackoverflow.com/questions/3634853/how-to-create-a-directory-in-java
'IT이야기' 카테고리의 다른 글
스프링 부트에서 필터 클래스를 추가하려면 어떻게 해야 하는가? (0) | 2022.05.11 |
---|---|
값을 기준으로 해시맵 정렬 (0) | 2022.05.11 |
vuex와 vue-router를 사용하여 백엔드와 프런트엔드 사이의 상태를 동기화하는 방법 (0) | 2022.05.11 |
인덱스에서 스플라이싱되지 않은 스플라이스는? (0) | 2022.05.11 |
구문 분석 방법구문 분석 방법VUE.js의 html 태그에 대한 문자열로VUE.js의 html 태그에 대한 문자열로 (0) | 2022.05.11 |