Java 中的 File.separator 和 new File()

在本教程中,我们将介绍构建文件路径的三个示例:
  • File.separator 或 System.getProperty(file.separator”)
  • File file = new File(path, filename)
  • 手动创建路径(不推荐)

File.separator

这是使用 File.separator 或 System.getProperty(file.separator”) 构造路径的经典方法。两者都将检查使用的操作系统并正确返回文件路径,例如:

1。Windows = \
2。Unix的;Linux 或 Mac = /
  
import java.io.File;
import java.io.IOException;

public class FileSeparator {
public static void main(String[] args) {
try {

String filename = nouveau_fichier.txt”;
字符串 currentdirectory= System.getProperty(user.dir”);

字符串 absoluteFilePath = ”;

absoluteFilePath = currentdirectory + File.separator + filename;

System.out.println(绝对路径:” + absoluteFilePath);

文件文件 = new File(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
File created!

new File()

调用 new File() 还允许您构建文件的路径。
  
import java.io.File;
import java.io.IOException;

public class NewFile {
public static void main(String[] args) {
try {

String filename = nouveau_fichier.txt”;
字符串 currentdirectory = System.getProperty(user.dir”);

文件文件 = new File(currentdirectory, filename);

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
File already exists.

手动构建路径

这种方法是要避免的,这里我们向您展示构建路径的所有方法.
  
import java.io.File;
import java.io.IOException;

public class NewFile {
public static void main(String[] args) {
try {

String filename = nouveau_fichier.txt”;
字符串 currentdirectory = 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) {

//if unix or mac
AbsolutePath = currentDirectory + /” + filename;

}else{
//找不到操作系统
AbsolutePath = currentdirectory + /” + filename;
}

System.out.println(路径:” + AbsolutePath);

文件文件 = new File(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
File already exists.
Resources:
http://java.sun.com/javase/6/docs/api/java/io/File.html