[java] Java FileOutputStream 존재하지 않는 경우 파일 작성

파일 (문자열 파일 이름)이 존재하지 않으면 파일을 생성하는 방식으로 FileOutputStream을 사용하는 방법이 있습니까?

FileOutputStream oFile = new FileOutputStream("score.txt", false);



답변

FileNotFoundException파일이 존재하지 않고 생성 할 수없는 경우 ( doc ) 를 던지지 만 가능하면 파일 을 만듭니다. 할 수 있는지 아마해야 당신이를 만들기 전에 파일이 존재하는지 첫 번째 테스트 FileOutputStream(과 함께 만들 createNewFile()그렇지 않은 경우)

File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 


답변

파일을 작성하기 전에 모든 상위 디렉토리를 작성해야합니다.

사용하다 yourFile.getParentFile().mkdirs()


답변

존재 여부에 관계없이 빈 파일을 만들 수 있습니다 …

new FileOutputStream("score.txt", false).close();

존재하는 경우 파일을 남기고 싶다면 …

new FileOutputStream("score.txt", true).close();

존재하지 않는 디렉토리에 파일을 작성하려고하면 FileNotFoundException 만 발생합니다.


답변

File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

이것을 생성자 f에게 전달하십시오 FileOutputStream.


답변

아파치 커먼즈의 FileUtils 는 한 줄로 이것을 달성하는 아주 좋은 방법입니다.

FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))

존재하지 않는 경우 상위 폴더를 작성하고 존재하지 않는 경우 파일을 작성하고 파일 오브젝트가 디렉토리이거나 쓸 수없는 경우 예외를 발생시킵니다. 이것은 다음과 같습니다 .

File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);

현재 사용자가 작업을 수행 할 수없는 경우 위의 모든 작업에서 예외가 발생합니다.


답변

존재하지 않는 경우 파일을 작성하십시오. 파일이 종료되면 내용을 지우십시오.

/**
 * Create file if not exist.
 *
 * @param path For example: "D:\foo.xml"
 */
public static void createFile(String path) {
    try {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        } else {
            FileOutputStream writer = new FileOutputStream(path);
            writer.write(("").getBytes());
            writer.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}


답변

경로 및 파일을 사용하여 존재하지 않는 경우에만 파일을 작성하는 다른 방법을 제공하십시오.

Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
    Files.createFile(path);
Files.write(path, ("").getBytes());