JAVA using relative path of reading a file list

Transfer from: http: //blog.csdn.net/yiluoak_47/article/details/7760385

Use a relative path java to read the file

1.java project environment, using examples java.io read the file using a relative path:
 * directory structure:
  DecisionTree
            | src ___
                 | ___ com.decisiontree.SamplesReader.java
            | Resource ___
                 | ___ train.txt, the Test. TXT
 * SamplesReader.java:
  String filepath = "Resource / train.txt"; // note the contents of filepath;
  File File = new new File (filepath);
  ......

 * we pay attention to the content filepath, java.io default to the current user directory ( "user.dir"), namely: the root Engineering

Catalog: the "D \ DecisionTree", therefore, at this time the relative path (path based user.dir path) is "resource / train.txt"

. In this way, JVM can get the full path based on "user.dir" and "resource / train.txt" (that is, absolute path

diameter) "D: \ DecisionTree \ resource \ train.txt", never found train.txt file.

 * Note: the start of the free diagonals relative path "
filepath = "resource / train.txt";
instead = filepath "/ Resource / train.txt"; // error!

2, javaEE environment, an example of using Classloader read xml with a relative path:
 * see previous article written by " xml file is read by a virtual path or a relative path, to avoid hard-coded. "

 * As follows:
 Java use a relative path to read xml file:
a, xml file storage location generally three:
1. Put the WEB-INF;
under 2.xml files in / WEB-INF / classes directory or the classpath jar package;
3. placed with its java parse a similar package, not necessarily the CLASSPATH;

two, corresponding to the relative path using two read methods:

method unverified :( a)
the discharge xml file in the WEB-INF directory, then the
program code:
the InputStream GetServletContext IS = () the getResourceAsStream ( "/WEB-INF/xmlfile.xml");.

method 2: xml files in / the WEB-INF / classes directory or classpath jar package, you can use a static ClassLoader

method getSystemResourceAsStream (String s) read;
program code:
S_xmlpath = String "COM / SPF / Web / EXT / Hotspot / hotspotxml / hotspot.xml";
the InputStream in = ClassLoader.getSystemResourceAsStream (s_xmlpath);

Method three: xml freely in the path of a packet:
String = s_xmlpath "COM / SPF /web/ext/hotspot/hotspotxml/hotspot.xml ";
ClassLoader HotspotXmlParser.class.getClassLoader classLoader = ();
the InputStream in = ClassLoader.getResourceAsStream (s_xmlpath);

Released two original articles · won praise 0 · Views 2507

Guess you like

Origin blog.csdn.net/yc_game/article/details/67632491