2013-06-30 52 views
0

我對Java中的路徑有困惑(使用Eclipse)。這是我的文件結構:Java:外部文本文件的相對路徑

Folder 

    Subfolder 

     file.txt 

    jarfile.jar 

所以,我試圖讓從file.txt的jar文件解析數據,我使用下面的代碼:

Scanner in = new Scanner(this.getClass().getResourceAsStream("./Subfolder/file.txt")); 

我做了一個可運行jar文件與Eclipse,把它放在文件夾中,但它不起作用。我做錯了什麼?

非常感謝!

Igor

+0

我不知道如果這是有幫助的 - 但我有時需要檢查我的代碼運行的位置,以找出相對路徑,所以我只需要執行'(new java.io.File(「。」)。getCanonicalPath()'。 – selig

回答

2

既然你通過Class對象使用一個資源文件,路徑到資源必須是絕對的:

getClass().getResourceAsStream("/Subfolder/file.txt"); 

注意,這樣做你做的是一個壞主意,那就是,打開掃描儀資源,你沒有參考:

new Scanner(someInputStreamHere()); 

你沒有參考輸入流,因此你不能關閉它。

更重要的是,如果資源不存在,.getResource*()返回null;在這種情況下,你會得到一個NPE!

建議,如果你使用Java 6(使用番石榴的更緊密):

final URL url = getClass().getResource("/path/to/resource"); 

if (url == null) // Oops... Resource does not exist 
    barf(); 

final Closer closer = Closer.create(); 
final InputStream in; 
final Scanner scanner; 

try { 
    in = closer.register(url.openStream()); 
    scanner = closer.register(new Scanner(in)); 
    // do stuff 
} catch (IOException e) { 
    throw closer.rethrow(e); 
} finally { 
    closer.close(); 
} 

如果使用Java 7中,只使用try-與資源聲明:

final URL url = getClass().getResource("/path/to/resource"); 

if (url == null) // Oops... Resource does not exist 
    barf(); 

final InputStream in; 
final Scanner scanner; 

try (
    in = url.openStream(); 
    scanner = new Scanner(in); 
) { 
    // do stuff 
} catch (IOException e) { 
    // deal with the exception if needed; or just declare it at the method level 
} 
+0

非常感謝你!這真是一種魅力! –

0

使用下面的代碼。 Scanner in = new Scanner(getClass()。getResource(「Subfolder/file.txt」));

+0

Nope ... '.getResource()'返回一個URL – fge

0

爲什麼資源? txt文件是嵌入在Jar文件中的嗎?它會從jar中加載文件。

只需使用File或FileInputStream和您已經放置的路徑即可。

1

就像一個例子,因爲Java是平臺獨立的看待獲得相對絕對或規範的路徑,我希望這給你一個想法做什麼。

/** 
* This method reads the AcronymList.xlsx and is responsible for storing historical acronyms 
* and definitions. 
* @throws FileNotFoundException 
* @throws IOException 
* @throws InvalidFormatException 
*/ 
public file readAcronymList() throws FileNotFoundException, IOException, InvalidFormatException { 
    String accListFile = new File("src\\org\\alatecinc\\acronymfinder\\dal\\acIgnoreAddList\\AcronymList.xlsx").getCanonicalPath(); 
    File acFile = new File(accListFile).getAbsoluteFile(); 
    return acFile; 
} 
+0

非常感謝! –