標籤:
比如我們有以下目錄
|--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擷取資源檔