Java擷取資源檔

來源:互聯網
上載者:User

標籤:

比如我們有以下目錄 
|--project 
    |--src 
        |--javaapplication 
            |--Test.java 
            |--file1.txt 
        |--file2.txt 
    |--build 
        |--javaapplication 
            |--Test.class 
            |--file3.txt 
        |--file4.txt 

在上面的目錄中,有一個src目錄,這是JAVA源檔案的目錄,有一個build目錄,這是JAVA編譯後檔案(.class檔案等)的存放目錄 
那麼,我們在Test類中應該如何分別獲得 
file1.txt file2.txt file3.txtfile4.txt這四個檔案呢? 

首先講file3.txt與file4.txt 
file3.txt: 
方法一:File file3 = newFile(Test.class.getResource("file3.txt").getFile()); 
方法二:File file3 = newFile(Test.class.getResource("/javaapplication/file3.txt").getFile()); 
方法三:File file3 = newFile(Test.class.getClassLoader().getResource("javaapplication/file3.txt").getFile()); 

file4.txt: 
方法一:File file4 = newFile(Test.class.getResource("/file4.txt").getFile()); 
方法二:File file4 = newFile(Test.class.getClassLoader().getResource("file4.txt").getFile()); 

但是file1與file2檔案只能寫上它們的絕對路徑,不能像file3與file4一樣用class.getResource()這種方法獲得,它們的擷取方法如下 (假設整個project目錄放在c:/下)
file1.txt 
File file1 = newFile("c:/project/src/javaapplication/file1.txt"); 

file2.txt 
File file2 = newFile("c:/project/src/file2.txt"); 

總結一下,就是你想獲得檔案,你得從最終產生的.class檔案為著手點,不要以.java檔案的路徑為出發點,因為真正使用的就是.class,不會拿個.java檔案就使用。

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.