2013-03-27 66 views
0

當我從jar文件中讀取一個文件並想將它放入一個jTextArea中時,它會顯示加密的符號,而不是真正的內容。Main.class.getResource()和jTextArea

我在做什麼:我讀文件

public File loadReadme() { 
    URL url = Main.class.getResource("/readme.txt"); 
    File file = null; 

    try { 
     JarURLConnection connection = (JarURLConnection) url 
       .openConnection(); 
     file = new File(connection.getJarFileURL().toURI()); 

     if (file.exists()) { 
      this.readme = file; 
      System.out.println("all ok!"); 

     } 
    } catch (Exception e) { 
     System.out.println("not ok"); 
    } 

    return file; 
} 

然後:

public ArrayList<String> readFileToArray(File file) { 
    ArrayList<String> array = new ArrayList<String>(); 
    BufferedReader br = null; 

    try { 

     String sCurrentLine; 
     br = new BufferedReader(new FileReader(file)); 
     while ((sCurrentLine = br.readLine()) != null) { 
      String test = sCurrentLine; 
      array.add(test); 

     } 

    } catch (IOException e) { 
     System.out.println("not diese!"); 

    } finally { 
     try { 
      if (br != null) 
       br.close(); 
     } catch (IOException ex) { 
     } 
    } 
    return array; 
} 

現在,我把所有的線從JTextArea中ArrayList中,這showes我這樣的事情:

PK 2 -S 3 Z_
%Q鉈7+;?? FK N :k ] Xk, U「 q \ % Q#4x | [ o S { :AG * SG」} nX5qhpuHW9h2Q# @ 7( @ F! 〜 j ?\xA/rr v l PK bv =

textfiled包含:

SELECTION: 
---------- 
By clicking the CTRL Key and the left mouse button you go in the selection mode. 
Now, by moving the mouse, you paint a rectangle on the map. 

DOWNLOAD: 
--------- 
By clicking on the download button, you start the download. 
The default location for the tiles to download is: <your home> 

我相信該文件存在! 有誰知道這個問題是什麼?我的「getResource」是否正確?

+0

readme.txt包含什麼內容?換句話說,你期望的輸出是什麼? – BackSlash 2013-03-27 09:37:01

+0

用此更新您的問題,我認爲可能有用 – BackSlash 2013-03-27 09:42:54

+0

做到了!對不起,我是初學者;) – 2013-03-27 09:43:56

回答

1

基於輸出,我懷疑你的代碼實際上讀取JAR文件本身(因爲它與PK開始)。爲什麼不使用下面的代碼讀取文本文件:

Main.class.getResourceAsStream("/readme.txt") 

這將使你的InputStream到文本文件沒有做打開JAR文件的麻煩,等

然後,您可以通過InputStream對象到readFileToArray方法(而不是File對象),並使用

br = new BufferedReader(new InputStreamReader(inputStream)); 

你的代碼的其餘部分應該不需要任何改變。

+0

現在怎麼做得更好?這實際上是可能的! – 2013-03-27 10:02:28

+0

恐怕我不明白你的評論... :( – mthmulders 2013-03-27 10:08:02

+0

我怎麼讀這個文件知道?我認爲這個文件是這個jar文件的當下! – 2013-03-27 10:10:42

0

這似乎是一個編碼的問題。 FileReader不允許你指定。嘗試使用

br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding)); 
+0

謝謝你,我正在使用Linux,我的文件被命名爲「自述文件」。txt「,你知道這個文件的編碼嗎? – 2013-03-27 09:46:14

+0

我不能告訴這個文件的編碼,只有這個文件的創建者可以告訴我這個 – SudoRahul 2013-03-27 09:47:24

0

你似乎在這裏爲自己做了太多的工作。你首先調用getResource,它給你一個到你的JAR文件中的readme.txt條目的URL,但是你接下那個URL,確定它所指向的JAR文件,然後用FileInputStream打開該JAR文件並讀取整個JAR文件。

可以代替簡單的調用.openStream()原始URL是getResource回來,這會給你一個InputStream,從中可以讀出的readme.txt

br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); 

的內容(如果readme.txt沒有在UTF-編碼8然後根據情況更改該參數)