Transferred from: http://blog.csdn.net/yiluoak_47/article/details/7760385
Java reads files using relative paths
1.java Project Environment, example of using java.io to read files with relative paths:
* Directory structure:
DecisionTree
|___src
|___com.decisiontree.samplesreader.java
|___resource
|___train.txt,test.txt
*samplesreader.java:
String filepath= "resource/train.txt";//Pay attention to the contents of filepath;
File File=new file (filepath);
......
* We pay attention to filepath content, java.io default to the current user directory ("User.dir"), that is: engineering root
"D:\DecisionTree", so that the relative path at this time (path with User.dir as the base path) is "Resource/train.txt"
。 This allows the JVM to get a complete path based on "User.dir" and "resource/train.txt" (i.e. absolute path
"D:\DecisionTree\resource\train.txt", never find the Train.txt file.
* Note: There is no diagonal "/" at the beginning of the relative path; for example:
Filepath= "Resource/train.txt";
Rather than filepath= "/resource/train.txt"; error!
2, Java EE environment, using ClassLoader with a relative path to read XML example:
* See previously written article "read an XML file from a virtual path or relative path to avoid hard coding."
* The contents are as follows:
Java reads the XML file using a relative path:
There are three general storage locations for XML files:
1. Place under the Web-inf;
2.xml files are placed in the/web-inf/classes directory or in the Classpath jar package;
3. In a package that is similar to the Java parsing it, it is not necessarily classpath;
Two, corresponding to the use of the relative path of the Read method:
Method One: (not verified)
Place the XML file in the Web-inf directory, and then
Program code:
InputStream Is=getservletcontext (). getResourceAsStream ("/web-inf/xmlfile.xml");
Method Two: Place the XML file in the/web-inf/classes directory or in the Classpath jar package, you can use the ClassLoader static
Method Getsystemresourceasstream (String s) reads;
Program code:
String s_xmlpath= "Com/spf/web/ext/hotspot/hotspotxml/hotspot.xml";
InputStream In=classloader.getsystemresourceasstream (S_xmlpath);
Method Three: XML at random under a package path:
String s_xmlpath= "Com/spf/web/ext/hotspot/hotspotxml/hotspot.xml";
ClassLoader Classloader=hotspotxmlparser.class.getclassloader ();
InputStream In=classloader.getresourceasstream (S_xmlpath);
JAVA reads files using relative paths