source

누락된 상위 디렉토리와 함께 새 파일을 만드는 방법은 무엇입니까?

goodcode 2022. 9. 11. 17:14
반응형

누락된 상위 디렉토리와 함께 새 파일을 만드는 방법은 무엇입니까?

사용시

file.createNewFile();

다음과 같은 예외가 있습니다.

java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb

누락된 부모 디렉토리를 만드는 create New File이 있습니까?

이거 먹어봤어?

file.getParentFile().mkdirs();
file.createNewFile();

이 작업을 수행할 수 있는 메서드 호출은 단 하나도 없지만 두 개의 문장으로는 매우 쉽습니다.

Jon의 답변은 파일을 작성할 때 사용하는 경로 문자열에 상위 디렉토리가 포함되어 있는 것이 확실한 경우(예: 경로 형식이 확실한 경우)에 유효합니다.<parent-dir>/<file-name>.

그렇지 않은 경우, 즉 양식의 상대 경로입니다.<file-name>,그리고나서getParentFile()돌아온다null.

예.

File f = new File("dir/text.txt");
f.getParentFile().mkdirs();     // works fine because the path includes a parent directory.

File f = new File("text.txt");
f.getParentFile().mkdirs();     // throws NullPointerException because the parent file is unknown, i.e. `null`.

따라서 파일 경로에 부모 디렉토리가 포함될 수도 있고 포함되지 않을 수도 있는 경우 다음 코드를 사용하는 것이 안전합니다.

File f = new File(filename);
if (f.getParentFile() != null) {
  f.getParentFile().mkdirs();
}
f.createNewFile();

Java7에서는 NIO2 API를 사용할 수도 있습니다.

void createFile() throws IOException {
    Path fp = Paths.get("dir1/dir2/newfile.txt");
    Files.createDirectories(fp.getParent());
    Files.createFile(fp);
}

언급URL : https://stackoverflow.com/questions/3090761/how-to-create-a-new-file-together-with-missing-parent-directories

반응형