java 使用相對路徑讀取檔案

來源:互聯網
上載者:User

java 使用相對路徑讀取檔案

1.java project環境,使用java.io用相對路徑讀取檔案的例子:
 *目錄結構:
  DecisionTree
            |___src
                 |___com.decisiontree.SamplesReader.java
            |___resource
                 |___train.txt,test.txt
 *SamplesReader.java:
  String filepath="resource/train.txt";//注意filepath的內容;
  File file=new File(filepath);
  ……

 *我們留意filepath的內容,java.io預設定位到目前使用者目錄("user.dir")下,即:工程根目

錄"D:\DecisionTree"下,因此,此時的相對路徑(以user.dir為基路徑的路徑)為"resource/train.txt"

。這樣,JVM就可以根據"user.dir"與"resource/train.txt"得到完整的路徑(即絕對路

徑)"D:\DecisionTree\resource\train.txt",從來找到train.txt檔案。

 *注意:相對路徑的起始處無斜杆"/";例如:
filepath="resource/train.txt";
而不是filepath="/resource/train.txt"; //error!

2、javaEE環境,使用Classloader用相對路徑讀取xml的例子:
 *參見之前寫的文章“通過虛擬路徑或相對路徑讀取一個xml檔案,避免寫入程式碼”。

 *內容如下:
 java使用相對路徑讀取xml檔案:
一、xml檔案一般的存放位置有三個:
1.放在WEB-INF下;
2.xml檔案放在/WEB-INF/classes目錄下或classpath的jar包中;
3.放在與解析它的java類同一個包中,不一定是classpath;

二、相對應的兩種使用相對路徑的讀取方法:

方法一:(未驗證)
將xml檔案放在WEB-INF目錄下,然後
程式碼:
InputStream is=getServletContext().getResourceAsStream( "/WEB-INF/xmlfile.xml" );

方法二:將xml檔案放在/WEB-INF/classes目錄下或classpath的jar包中,則可以使用ClassLoader的靜態

方法getSystemResourceAsStream(String s)讀取;
程式碼:
String s_xmlpath="com/spf/web/ext/hotspot/hotspotxml/hotspot.xml";
InputStream in=ClassLoader.getSystemResourceAsStream(s_xmlpath);

方法三:xml在隨意某個包路徑下:
String s_xmlpath="com/spf/web/ext/hotspot/hotspotxml/hotspot.xml";
ClassLoader classLoader=HotspotXmlParser.class.getClassLoader();
InputStream in=classLoader.getResourceAsStream(s_xmlpath);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.