Java의 File.separator 및 new File()
이 튜토리얼에서는 파일 경로를 작성하기 위한 세 가지 예를 살펴보겠습니다.
- File.separator or System.getProperty("file.separator")
- File file = new File(path, filename)
- 수동으로 경로 만들기(권장하지 않음)
File.separator
이것은 File.separator 또는 System.getProperty("file.separator")를 사용하여 경로를 생성하는 고전적인 방법입니다. 둘 다 사용된 운영 체제를 확인하고 파일 경로를 올바르게 반환합니다(예:
1). 윈도우 = \
2. 유닉스; Linux 또는 Mac = /
import java.io.File;
import java.io.IOException;
public class FileSeparator {
public static void main(String[] args) {
try {
문자열 파일 이름 = "nouveau_fichier.txt";
문자열 currentdirectory= System.getProperty("user.dir");
문자열 absoluteFilePath = "";
absoluteFilePath = 현재 디렉토리 + File.separator + 파일 이름;
System.out.println("절대 경로: " + absoluteFilePath);
파일 파일 = 새 파일(absoluteFilePath);
if (file.createNewFile()) {
System.out.println("파일이 생성되었습니다!");
} else {
System.out.println("파일이 이미 존재합니다.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
출력:
절대 경로: C:\Documents and Settings\Poste07\workspace\File\nouveau_fichier.txt
파일 생성됨!
new File()
new File()을 호출하면 파일의 경로를 작성할 수도 있습니다.
import java.io.File;
import java.io.IOException;
public class NewFile {
public static void main(String[] args) {
try {
문자열 파일 이름 = "nouveau_fichier.txt";
현 현재 디렉토리 = System.getProperty("user.dir");
파일 파일 = 새 파일(현재 디렉토리, 파일 이름);
System.out.println("경로: " + file.getAbsolutePath());
if (file.createNewFile()) {
System.out.println("파일이 생성되었습니다!");
} else {
System.out.println("파일이 이미 존재합니다.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
출력:
경로: C:\Documents and Settings\Poste07\workspace\File\nouveau_fichier.txt
파일이 이미 있습니다.
수동으로 경로 작성
이 방법은 피해야 하며, 여기서는 경로를 작성하는 모든 방법을 보여줍니다.
http://java.sun.com/javase/6/docs/api/java/io/File.html
import java.io.File;출력:
import java.io.IOException;
public class NewFile {
public static void main(String[] args) {
try {
문자열 파일 이름 = "nouveau_fichier.txt";
현 현재 디렉토리 = System.getProperty("user.dir");
문자열 AbsolutePath = "";
문자열 os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("win") >= 0) {
//if windows
Absolutepath = currentdirectory + "\\" + filename;
} else if (os.indexOf("nix") >= 0 ||
os.indexOf("nux") >= 0 ||
os.indexOf("mac") >= 0) {
//유닉스 또는 맥인 경우
AbsolutePath = currentDirectory + "/" + 파일 이름;
}else{
//OS를 찾을 수 없음
AbsolutePath = currentdirectory + "/" + filename;
}
System.out.println("경로: " + AbsolutePath);
파일 파일 = 새 파일(AbsolutePath);
if (file.createNewFile()) {
System.out.println("파일 생성됨");
} else {
System.out.println("파일이 이미 존재함");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
경로: C:\Documents and Settings\Poste07\workspace\File\nouveau_fichier.txt리소스:
파일이 이미 있습니다.
http://java.sun.com/javase/6/docs/api/java/io/File.html