(a) Function: (1) class.getresource (String path)
(2)Class.getClassLoader.getResource (String Path)
where path in (2) cannot begin with '/' (1) path has no '/' both, meaning is different
TwoTo test the directory structure:
|--project
|--src
|--mytest
|--repathtest.java
|--file1.t Xt
|--file2.txt
|--bin
|--mytest
|--repatht Est.class
< c21> |--file3.txt
|--file4.txt
(c) Usage: (2) By default is obtained from classpath (i.e. bin or classes path)in this example:
file file3 =
new file (repathtest.
Class. getClassLoader (). GetResource ("Mytest/file3.txt"). GetFile ()); file file4 =
new file (repathtest.
Class. getClassLoader (). GetResource ("File4.txt"). GetFile ());
(1) MediumA. Start with a '/' and represent theClassPath (i.e. bin or classes path) getsIn this example:file file3 =
new file (repathtest.
Class. GetResource ("/mytest/file3.txt"). GetFile ()); Search from Classpath bin
B. Not to'/', indicating the relativepath of the Repathtest.classin this example:file file3 =
new file (repathtest.
Class. GetResource ("File3.txt"). GetFile ());//From package mytest, relative to. Class (Hererepathtest.
class) file
(iv) getResourceAsStream () vs Getresouce ()getResourceAsStream () method, the parameter is the same as the Getresouce () method, which is equivalent to the same result as when you get the file with GetResource (), and then new InputStream (file)
(v) Supplementary1. Classes files in Web-inf in the WEB as Classpath directory2. GetResource gets the path associated with the. class folder, regardless of the. Java folder
(vi) Testing
package mytest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class repathtest { repathtest Test =
new repathtest ();Public
static
void main (string[] args)
throws FileNotFoundException {file file3 =
new file (repathtest.
Class. GetResource ("File3.txt"). GetFile ()); //file file3 = new File (RePathTest.class.getResource ("/mytest/file3. TXT"). GetFile ()); //file file3 = new File (RePathTest.class.getClassLoader (). GetResource ("mytest/file3. TXT"). GetFile ()); FileReader fr =
new filereader (file3);BufferedReader br =
new bufferedreader (fr);
try {String line = br. ReadLine ();while (line!
=
null) { System. Out. Print (line);
Line = br. ReadLine (); }}
Catch (IOException e) { e. Printstacktrace (); } //file file4 = new File (RePathTest.class.getResource ("/file4"). TXT"). GetFile ()); //file file4 = new File (RePathTest.class.getClassLoader (). GetResource ("File4. TXT"). GetFile ()); }}
Reference:http://blog.163.com/[email protected]/blog/static/1697674882011112045456653/http://www.cnblogs.com/javayuer/archive/2011/01/02/1924192.html
Java relative path acquisition--Application of GetResource