public class testPath {
public static void main(String[] args) {
System.out.println(System.getProperty("java.class.path"));//Java 類別路徑
System.out.println(System.getProperty("user.dir"));//用戶的當前工作目錄
//System.getProperty("user.dir") + "/filename" ,較安全的相對路徑
String basePathR = new File("").getPath();
System.out.println("getPath:"+basePathR);
String basePathA = new File("").getAbsolutePath();
System.out.println("getAbsolutePath:"+basePathA);
try {
String basePathC = new File("").getCanonicalPath();
System.out.println("getCanonicalPath:"+basePathC);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("=releative path=============");
FileWriter writer = null;
try {
File file = new File("releative.txt");
writer = new FileWriter(file);
writer.write("test re");
displayPath(file);
} catch (IOException e) {
System.out.println("releative:" + e.getMessage());
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
System.out.println("=absolute path=============");
try {
File file = new File("/candelete/absolute.txt");
writer = new FileWriter(file);
writer.write("test ab");
displayPath(file);
} catch (IOException e) {
System.out.println("absolute:" + e.getMessage());
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
}
public static void displayPath(File testFile) {
System.out.println("path : " + testFile.getPath());
System.out.println("absolute path : " + testFile.getAbsolutePath());
try {
System.out.println("canonical path : "
+ testFile.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
輸出結果:
C:\Users\Melody\workspace_web\testJava\bin
C:\Users\Melody\workspace_web\testJava
getPath:
getAbsolutePath:C:\Users\Melody\workspace_web\testJava
getCanonicalPath:C:\Users\Melody\workspace_web\testJava
=releative path=============
path : releative.txt
absolute path : C:\Users\Melody\workspace_web\testJava\releative.txt
canonical path : C:\Users\Melody\workspace_web\testJava\releative.txt
=absolute path=============
path : \candelete\absolute.txt
absolute path : C:\candelete\absolute.txt
canonical path : C:\candelete\absolute.txt
沒有留言:
張貼留言