java file path abstract path absolute path canonical path

  1. path,普通路径名,由getPath()方法返回,就是你构造File时指定路径名。如File f = new File("testFile.txt");则f.getPath()返回的就是"testFile.txt".
2.abstract pathname,根据File的toString方法的说明,这个也是getPath()返回的结果,和上面的一样。
String java.io.File.toString()
Returns the pathname string of this abstract pathname. This is just the string returned by the getPath method. 

3. absolute path,未修饰的绝对路径,像表示上一级路径的符号"..",在absolute path中是直接显示的。
如File abstractf = new File("..\\testFile.txt");
System.out.println(abstractf.getAbsolutePath());
结果就是 D:\springWorkSpace\Fortest\..\testFile.txt

4. canonical path:修饰过的绝对路径。上面abstractf路径中的".."会被解释成上一级路径。如:
System.out.println(abstractf.getAbsolutePath());
结果就是 D:\springWorkSpace\testFile.txt

public static void main(String[] args){
		try {
			File f = new File("testFile.txt");
			File abstractf = new File("..\\testFile.txt");
			File emptyf = new File("");
			System.out.println("f's abstract path:" + f.getPath());
			System.out.println("f.getAbsolutePath():" + f.getAbsolutePath());
			System.out.println("f.getCanonicialPath():" + f.getCanonicalPath());
			System.out.println("abstractf's abstract path:" + abstractf.getPath());
			System.out.println("abstractf.getAbsolutePath():" + abstractf.getAbsolutePath());
			System.out.println("abstractf.getCanonicialPath():" + abstractf.getCanonicalPath());
			System.out.println("emptyf's abstract path:" + emptyf.getPath());
			System.out.println("emptyf.getAbsolutePath():" + emptyf.getAbsolutePath());
			System.out.println("emptyf.getCanonicialPath():" + emptyf.getCanonicalPath());


			File newFile = new File(emptyf,"newFile.txt");
			System.out.println("-------------");
			System.out.println("newFile's abstract path: " + newFile.getPath());
			System.out.println("newFile's absolute path: " + newFile.getAbsolutePath());
			System.out.println("newFile's canonicial path: " + newFile.getCanonicalPath());

			FileWriter newWriter = new FileWriter(newFile);
			newWriter.write("new test data");
			newWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

输出:

f's abstract path:testFile.txt
f.getAbsolutePath():D:\springWorkSpace\Fortest\testFile.txt
f.getCanonicialPath():D:\springWorkSpace\Fortest\testFile.txt
abstractf's abstract path:..\testFile.txt
abstractf.getAbsolutePath():D:\springWorkSpace\Fortest\..\testFile.txt
abstractf.getCanonicialPath():D:\springWorkSpace\testFile.txt
emptyf's abstract path:
emptyf.getAbsolutePath():D:\springWorkSpace\Fortest
emptyf.getCanonicialPath():D:\springWorkSpace\Fortest
-------------
newFile's abstract path: \newFile.txt
newFile's absolute path: D:\newFile.txt
newFile's canonicial path: D:\newFile.txt

你可能感兴趣的:(java file path abstract path absolute path canonical path)