1. 程式人生 > >Java中讀取classpath下的檔案

Java中讀取classpath下的檔案

專案的工程目錄入如下: 在這裡插入圖片描述

從類路徑(classpath)下讀取檔案:

我們讀取resources目錄下的StringUtils.java檔案。 介紹幾種常見的方法:

1.使用絕對路徑法:
        File file = new File("D:\\ideaprojects\\qunar_works\\src\\main\\resources\\StringUtils.java");
        // 獲取檔案的檔名稱
        System.out.println(file.getName());

缺點:與本地磁碟路徑相關,可移植性太差。

2.使用相對路徑(推薦使用)
URL resource =
StatisticCodeLines.class.getClassLoader().getResource("StringUtils.java"); File file = new File(resource.getFile()); System.out.println(file.getName());
3.介紹其他幾種api:

1.`獲取一個inputStream檔案輸入流

    // 表示這樣也可以從類路徑下獲取檔案,只不過返回一個InputStream 物件
     InputStream inputStream = StatisticCodeLines.
class.getClassLoader().getResourceAsStream("StringUtils.java");
4.利用字元流讀取檔案,寫入檔案