I was a rookie, routing problem often makes me confused at the time of writing project, so to write this summary.
A relative path
1, the relative path in Java, JVM startup path is relative, and in general is started under the project name.
In the example here I use Eclipse to write, which is the directory test project
Sample code:
public class Demo1 { public static void main(String[] args) throws Exception{ File f1 = new File("test1.txt"); File f2 = new File("./test2.txt"); File f3 = new File("src/test3.txt"); File f4 = new File("test4.txt"); System.out.println(f1.exists()+":"+f1.getCanonicalPath()); System.out.println(f2.exists()+":"+f2.getCanonicalPath()); System.out.println(f3.exists()+":"+f3.getCanonicalPath()); System.out.println(f4.exists()+":"+f4.getCanonicalPath()); } }
Output:
true:D:\spam\path\test1.txt true:D:\spam\path\test2.txt true:D:\spam\path\src\test3.txt false:D:\spam\path\test4.txt
Description:
① From the example we can see all the files are relative to D: \ spam \ path the path established.
All the same semantic ② "./ test2" and "test1" represented, as opposed to the current JVM startup directory
③ "../ test" indicates the current directory with a directory on
④test4 tell us File semantic representation is only one path
2、getPath()、getAbsolutePath()、getCanonicalPath()区别
Example:
public class Demo1 { public static void main(String[] args) throws Exception{ File f1 = new File("test1.txt"); File f2 = new File("./test2.txt"); File f3 = new File("src/test3.txt"); System.out.println(f1.exists()+":"+f1.getPath()); System.out.println(f2.exists()+":"+f2.getAbsolutePath()); System.out.println(f2.exists()+":"+f2.getCanonicalPath()); System.out.println(f2.exists()+":"+f2.getPath()); System.out.println(f3.exists()+":"+f3.getCanonicalPath()); } }
Output:
true:test1.txt true:D:\spam\path\.\test2.txt true:D:\spam\path\test2.txt true:.\test2.txt true:D:\spam\path\src\test3.txt
Description:
①getPath (): When you can see the string get is to create File
②getAbsolutePath (): get the absolute path is not parsed
③getCanonicalPath (): get the absolute path specification
3, load the file Class.getResource (String path)
Example:
public class Demo2 { public static void main(String[] args) throws Exception{ Class<?> c = Demo2.class; System.out.println(c.getResource("")); System.out.println(c.getResource("/")); System.out.println(c.getResource("").toURI()); File f1 = new File(c.getResource("/test3.txt").toURI()); System.out.println(f1.exists()+":"+f1.getPath()); } }
Output:
file:/D:/spam/path/bin/test/ file:/D:/spam/path/bin/ file:/D:/spam/path/bin/test/ true:D:\spam\path\bin\test3.txt
Description:
getResource (String path) General method for loading a file, and with respect to D: / spam / path / bin directory,
bin directory and the src directory corresponds substantially to, bin directory for .class file src directory for .java files.
Absolute path is not to say, quite simply nothing to say.