사용할 때
file.createNewFile();
다음 예외가 발생합니다.
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
누락 된 상위 디렉토리를 생성하는 createNewFile이 있는지 궁금합니다.
답변:
이거 해봤 어?
file.getParentFile().mkdirs();
file.createNewFile();
이 작업을 수행 할 단일 메서드 호출을 모르지만 두 개의 문으로 매우 쉽습니다.
mkdirs생성하려는 파일이 존재하지 않는 디렉토리에 있지 않으면 필요 하지 않지만 내 사용 사례는 여러 파일을 생성하는 것 입니다. 그 중 일부 는 상위 디렉토리가 있고 다른 파일은 그렇지 않습니다.
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();
new File("file.txt").getParentFile()수익을null,new File("dir/file.txt").getParentFile()같은를 반환new File("dir")