2010-05-14 4 views
172

FileWriter으로 새 파일을 쓰고 싶습니다. 나는이처럼 사용 새 파일에 쓸 때 전체 경로 자동 생성

FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt"); 

지금 dir1dir2가 현재 존재하지 않습니다. 자바가 이미 존재하지 않는다면 자동으로 자바를 생성하기를 원한다. 실제로 Java는 전체 파일 경로를 아직 설정하지 않은 경우이를 설정해야합니다.

어떻게하면됩니까?

답변

306

뭔가 :

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt"); 
file.getParentFile().mkdirs(); 
FileWriter writer = new FileWriter(file); 
+3

왜 getParentFile이 아니라 mkdirs입니까? – sauperl

+22

@sauperl : 그러면'filename.txt'라고하는 * 디렉토리 *가 생성 될 것입니다 ... –

15

File.mkdirs()을 사용하십시오.

+1

+1 : \\ 파일 이름 \ 바탕 화면 \ DIR1 \ DIR2 \ 사용자하십시오 _directory_'C를 생성 할 문서 – ted

+1

을 인용. txt \'. –

+0

@ MartinSchröder : 파일 이름 구성 요소 만 유지해야합니다. –

22

사용 File.mkdirs() : 같은

File dir = new File("C:\\user\\Desktop\\dir1\\dir2"); 
dir.mkdirs(); 
File file = new File(dir, "filename.txt"); 
FileWriter newJsp = new FileWriter(file); 
4

사용 FileUtils이 모든 두통을 처리 할 수.

편집 : 예를 들어 아래 코드를 사용하여 파일에 쓰면이 방법은 '존재하지 않는 경우 부모 디렉토리를 확인하고 생성합니다'.

openOutputStream(File file [, boolean append]) 
+1

좀 더 구체적으로 말씀해 주시겠습니까? – Jean

+0

안녕 Jean, 편집 됨. FileUtils에는 다른 유용한 메서드가 많이 있습니다. OIUtils 및 FileUtils와 같은 Apache Commons IO 클래스는 Java 개발자의 생활을 더 쉽게 만듭니다. – kakacii

+0

필자는 FileUtils가 좋은 방법이라는 데 동의하지만, 더 쉬운 방법은 openOutputStream이 아닌 writeStringToFile을 사용하는 것이라고 생각합니다. 예 : 파일 file = 새 파일 ("C : /user/Desktop/dir1/dir2/filename.txt"); FileUtils.writeStringToFile (파일 "foo bar baz", true); – paul

92

자바 1.7 이후 당신은 Files.createFile를 사용할 수 있습니다

Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt"); 
Files.createDirectories(pathToFile.getParent()); 
Files.createFile(pathToFile); 
+2

상대 경로로 인해 null이 발생할 수 있음을 명심하십시오. 포인터 예외. 'Path pathToFile = Paths.get ("myFile.txt"); Files.createDirectories (pathToFile.getParent());' – Mag

관련 문제