这篇文章介绍两种构造文件路径的方法:
1.检查操作系统类型,然后手工创建路径分隔符(不推荐)
2.使用java File类中的
File.separator(最佳实践)
File.separator 会检查你的操作系统,并显示正确的分隔符,例如:
1. Windows下--返回 "\"
2. *nix下--返回"/"
手工创建文件分隔符的例子:
- package org.hnrsc.io;
-
-
import java.io.File;
-
import java.io.IOException;
-
-
//
-
public class JavaFileIO {
-
-
public static void main(String[] args){
-
try{
-
String filename = "test.txt";
-
String finalfile = "";
-
String workingDir = System.getProperty("user.dir");
-
-
String your_os = System.getProperty("os.name").toLowerCase();
-
if(your_os.indexOf("win") >= 0){
-
finalfile = workingDir + "\\" + filename;
-
}else if(your_os.indexOf("nix")>=0 || your_os.indexOf("nux")>=0){
-
finalfile = workingDir + "/" +filename;
-
}else{
-
finalfile = workingDir + "{other}" + filename;
-
}
-
System.out.println("Final filepath: " + finalfile);
-
-
File file = new File(finalfile);
-
-
if(file.createNewFile()){
-
System.out.println("File is created");
-
}else{
-
System.out.println("File already exisit.");
-
}
-
}catch(IOException e){
-
e.printStackTrace();
-
}
-
}
-
}
使用File.separator的例子:
- package org.hnrsc.io;
-
-
import java.io.File;
-
import java.io.IOException;
-
-
//
-
public class JavaFileIO {
-
-
public static void main(String[] args){
-
try{
-
String filename = "test1.txt";
-
String finalfile = "";
-
String workingDir = System.getProperty("user.dir");
-
-
//The system-dependent default name-separator character, represented as a string for convenience
-
finalfile = workingDir + File.separator + filename;
-
-
System.out.println("Final filepath: " + finalfile);
-
-
File file = new File(finalfile);
-
-
if(file.createNewFile()){
-
System.out.println("File is created");
-
}else{
-
System.out.println("File already exisit.");
-
}
-
}catch(IOException e){
-
e.printStackTrace();
-
}
-
}
-
}
阅读(1244) | 评论(0) | 转发(0) |