2012-03-03 44 views
2

我無法從URL做一個XML文件的一個簡單的下載URL的XML/RDF文件。我已經查看了一下這個網站已經有一段時間了,並且遵循了大多數關於如何使用正確的編碼下載文件的例子,但是我必須做一些錯誤的事情,因爲我沒有獲得所需的輸出。目前我的代碼看起來像這樣。從下載使用Java

  Catalog cat = (Catalog)obj; 

      String datasetURL = cat.getID()+"@datasets"; 

      URL dataURL = new URL(datasetURL); 

      InputStream iStream = dataURL.openStream(); 

      int count = iStream.available(); 
      char content[] = new char[count]; 

      InputStreamReader isReader = new InputStreamReader(iStream,"UTF-8"); 

      BufferedReader buffRead = new BufferedReader(isReader); 

      buffRead.read(content, 0, count); 

      String contentAsString = new String(content, 0,count); 

      FileWriter fstream = new FileWriter("src/main/resources/datasets.xml"); 
      BufferedWriter out = new BufferedWriter(fstream); 

      out.write(contentAsString); 
      out.close(); 

這似乎但是XML文件是這樣顯示的字符才能正常工作: Ksǵp等在Eclipse和�KsÇμ���Žp�在記事本中出現++。我不知道該怎麼做,因爲我已經將編碼添加到InputStreamReader,所以我認爲這將解決這個問題。

而且我也不是太熟悉RDF,但XML文件的RDF標籤在裏面。這會有什麼不同嗎?

<?xml version='1.0' encoding='UTF-8'?> 
<r:RDF xmlns:s="http://www.w3.org/TR/1999/PR-rdf-schema-19990303#" xmlns:r="http://www.w3.org/1999/02/22-rdf-syntax-ns#" etc.. 

非常感謝。

回答

0

我發現這個問題實際上是因爲該文件是壓縮!這裏是我現在使用的代碼,它已經成功下載了這個文件。

  Catalog cat = (Catalog)obj; 

      indexName += "."+cat.getInternalID(); 

      String datasetURL = cat.getID()+"@datasets"; 

      URL dataURL = new URL(datasetURL); 

      URLConnection conn = dataURL.openConnection(); 

      String encoding = conn.getContentEncoding(); 

      InputStream is = encoding.equals("gzip")? new GZIPInputStream(conn.getInputStream()) : conn.getInputStream(); 

      BufferedReader in = new BufferedReader(new InputStreamReader(is)); 

      String inputLine; 

      while ((inputLine = in.readLine()) != null) 
       System.out.println(inputLine); 

      in.close(); 

希望這可以幫助那些可能有類似問題的人。

3

您沒有提供charset給構造函數的字符串。

你可能想看看Guava,它有一些很不錯的工具,用於在文件和URL,除其他事項外的內容閱讀。

如果您打算使用RDF,我建議您嘗試使用SesameJena

+0

謝謝你的回答邁克爾,那些是一些非常好的資源,我很感謝你的幫助。 – decal 2012-03-07 16:13:23