파일 생성 (절대 경로)
File()
의 인자로 절대경로를 전달하여 파일 객체를 생성할 수 있습니다.
파일 객체는 그 경로를 가리키는 파일일 뿐, 실제로 파일이 생성되는 것은 아닙니다.
Files.touch()
의 인자로 파일 객체를 전달하면, 실제 파일이 생성됩니다.
다음과 같이 특정 경로에 파일을 생성할 수 있습니다.
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File file = new File(tempDir + "/text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());
Files.touch(file);
System.out.println(file.exists());
Output:
/tmp/text.txt
false
true
직접 파일 경로를 절대경로로 입력할 수 있었지만, 플랫폼마다, 사용자마다 경로가 다를 수 있기 때문에
System.getProperty("java.io.tmpdir")
으로 시스템에서 임시로 사용할 수 있는 temp directory 경로를 얻었습니다.
File.separator
Directory를 구분할 때는 /
, \
등 OS마다 다른 구분자를 사용할 수 있습니다.
File.separator
는 플랫폼에서 사용하는 구분자를 리턴해 줍니다.
Windows, Linux 등의 다양한 플랫폼에서 동작하는 코드라면 File.separator
를 사용해야 합니다.
File.separator
를 사용하여 다음과 같이 구현할 수 있습니다.
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File file = new File(tempDir + File.separator + "text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());
Files.touch(file);
System.out.println(file.exists());
Output:
/tmp/text.txt
false
true
파일 생성 (상대 경로)
File(tempDir, "text.txt")
와 같이 파일을 생성하면 tempDir의 경로에 text.txt
파일이 생성됩니다.
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File file = new File(tempDir, "text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());
Files.touch(file);
System.out.println(file.exists());
Output:
/tmp/text.txt
false
true
Loading script...