Java程式中讀取外部檔案時的路徑問題

來源:互聯網
上載者:User

標籤:工程   運行時   out   資料   etc   resource   另一個   方式   設定檔   

轉自:https://www.cnblogs.com/wt20/p/8320346.html

項目經常會讀取一些設定檔, 因此getResource方法便能夠起到重要作用

使用時主要是兩種方法, 一個是位元組碼檔案Class類, 另一個是ClassLoader類載入器

使用Class類時有兩種使用方式:

1. 使用"/"  擷取到的是classpath路徑

2. 不使用"/" 這就是相對路徑

ClassLoader類

沒有"/"的寫法, 擷取到的就是classpath路徑

測試代碼

public class GetResourceTest {    public static void main(String[] args) {        System.out.println(GetResourceTest.class.getResource("/test.properties").getPath());        System.out.println(GetResourceTest.class.getResource("test1.properties").getPath());        System.out.println(GetResourceTest.class.getClassLoader().getResource("test.properties").getPath());        System.out.println(GetResourceTest.class.getClassLoader().getResource("/"));    }}

結果:

/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
/E:/IdeaJava/studyTest/out/production/studyTest/com/waston/Test/test1.properties
/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
null

工程包結構

以上為https://www.cnblogs.com/wt20/p/8320346.html博主所寫

 

最近在做項目時需要對資料庫的曆史資料進行處理,由於對oracle資料庫的定時任務不熟悉所以使用Java編寫了一個定時任務

在程式中需要讀取一個ctl檔案,但是,如果給定目錄的話,給客戶運行時可能由於檔案放在位置出錯而不能讀取到檔案,嘗試使用虛擬路徑,沒有成功,在網上搜到使用此方法可以擷取到目錄,嘗試使用,成功。

 

 

 

 

 

 

Java程式中讀取外部檔案時的路徑問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.