ProgramingTip

Java의 createNewFile ()-디렉토리도 생성 또는 생성?

bestdevel 2020. 10. 13. 08:13
반응형

Java의 createNewFile ()-디렉토리도 생성 또는 생성?


진행하기 전에 특정 파일이 있는지 확인하는 조건이 있습니다 ./logs/error.log. 당신은 당신을 만들고 싶습니다. 그러나

File tmp = new File("logs/error.log");
tmp.createNewFile();

logs/존재하지 않고 생성 하시겠습니까?


아니요 . 파일을 만들기 전에
사용하십시오 tmp.getParentFile().mkdirs().


File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();

File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();

디렉토리가 이미 존재하는 경우 아무 일도 일어나지 검사 할 필요가 없습니다.


자바 8 스타일

Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());

파일에 쓰려면

Files.write(path, "Log log".getBytes());

읽다

System.out.println(Files.readAllLines(path));

전체 예

public class CreateFolderAndWrite {

    public static void main(String[] args) {
        try {
            Path path = Paths.get("logs/error.log");
            Files.createDirectories(path.getParent());

            Files.write(path, "Log log".getBytes());

            System.out.println(Files.readAllLines(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

StringUtils.touch(/path/filename.ext) 이제 (> = 1.3) 디렉토리와 파일이 존재하지 않는 존재하지 생성합니다.


아니요, logs존재하지 않습니다.java.io.IOException: No such file or directory

안드로이드 DEVS에 대한 재미있는 사실은 :의 좋아하는 통화 Files.createDirectories()Paths.get()분 API (26)를 지원할 때 작동합니다.

참고 URL : https://stackoverflow.com/questions/6666303/javas-createnewfile-will-it-also-create-directories

반응형