programing

Java의 create New File() - 디렉토리도 작성합니까?

coolbiz 2022. 10. 5. 23:02
반응형

Java의 create New File() - 디렉토리도 작성합니까?

전에 특정 ./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();

디렉토리가 이미 존재하는 경우 아무 일도 일어나지 않으므로 체크가 필요하지 않습니다.

Java 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

의 재미있는 사실: Android와 합니다.Files.createDirectories() ★★★★★★★★★★★★★★★★★」Paths.get() 26min api 26을 합니다.

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

반응형