Usually we locate files are located by absolute path, such as "F:/java/bin/test/test.java", the disadvantage is that once the project files moved, these paths are completely invalidated.
So, let's describe a way to locate a file through a relative path. The IDE I used is eclipse, the project path has src and bin folders stored separately, Java source code and compiled files.
, my project name is Project, in the F-Disk study directory, the package name is com.www, the source file is Test.java
We know that Java source files are compiled before they can be run, That is, Java is actually running Ttest.class, and Test.class in the bin file directory, with the SRC directory is not related, then if you want to locate the SRC directory files, you can only use the absolute path to locate.
The following discussion, using relative paths to locate files in the bin directory, we want to locate Test33.xml, Test22.xml, Test11.xml. Defines a class named Test,new as an instance of Te.
Start by locating the class:
Adoption class: Test.class.getClass ()
With instance: Te.getclass (), when an object is called, you can use This.getclass ()
Positioning Www.txt
Method One: String Str11 = Te.getclass (). GetResource ("Www.txt"). GetFile (), Printed display:/d:/study/project/bin/com/www/www.txt
If you want a file of type files, using the GetFile () method, the Www.txt is replaced with/com/www/www.txt to get the same result, which means that the Getresoure () method is the bin directory as the root directory, You can locate any file in the bin directory, except that it starts looking up from the directory where the class file is located . (I tried to locate the file inside the PROJRCT, it won't work)
Method Two: String str = Te.getclass (). getClassLoader (). GetResource ("Bin.txt"). GetPath (); Print Display:/d:/study/project/bin/bin.txt
If you want to locate the Www.txt file, you can change the bin.txt to/com/www/www.txt, and also the bin directory as the root directory, but from the bin directory to start looking down . (not in the same bin directory)
Adding the getClassLoader () method actually turns the starting directory from the class file directory to the root directory.
Common methods:
The Getresourse () method returns a URL type object that appears to be commonly used only by the GetPath () and GetFile () methods on the location file.
If you want a file,file file = new file (Te.getclass (). GetResource ("Www.txt"). Touri ()) or
New File (Te.getclass (). GetResource ("Bin.txt"). GetFile ())
The getClassLoader () method returns a ClassLoader type Object, and he also has the Getresourse () method, which is the equivalent of adding a layer, and the back is the same.
The getResourceAsStream () method returns a InputStream type Object
Using relative paths to locate files in Java