2014-02-10 119 views
0

我有一個指向服務器存儲庫位置的鏈接列表,Links代表一些資源,包括圖像,xml,txt,csv(每個不同大小)的文件,但是我面臨的問題是,當我下載文件所有下載的文件具有相同的文件大小。從URL下載資源java

List<String> Links;//list of links dynamically populated 
for(String link:Links) 
{ 
    int i=link.lastIndexOf("/"); 
    String temp=link.substring(0, i); 
    String contentname = temp.substring(temp.lastIndexOf("/")+1); 
    String filePath = tempFolderPath + "\\" + contentname; 
    URL url = new URL(link); 
    URLConnection connection = url.openConnection(); 
    InputStream is = new DataInputStream(connection.getInputStream()); 
    FileOutputStream fos = null; 
    try { 
     fos = new FileOutputStream(new File(filePath)); 
     int inByte; 
     while((inByte = is.read()) != -1) 
      fos.write(inByte); 
     is.close(); 
     fos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    finally 
    { 
     try { 
      is.close(); 
      fos.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

其中鏈接直接訪問的源泉「//localhost:8090/documents/11234/13935/abc.txt」

+0

下載的文件是什麼?實際內容?別的東西? – jtahlborn

+0

如果我打開下載的圖像類型jpg,png它不會打開和其他文件包含數據,但不完整的數據。 – Ali

+0

你是否收到異常? – jtahlborn

回答

-1

使用,而不是它僅用於Java對象一個DataInputStream一個的BufferedInputStream流。


InputStream is = connection.getInputStream(); 
FileOutputStream fos = null; 
try { 
    Files.copy(is, new File(filePath)); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

隨着問題依然存在:

要下載HTML我做了一個額外的事情:我僞造是一個瀏覽器。

PrintWriter out = null; 
    try { 
     out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), 
       StandardCharsets.ISO_8859_1)), true); 
     // We use the standard for our own headers: Latin-1 and "\r\n". 

     // Set our own headers, gotten from Firefox TamperData plugin. 
     out.print("GET " + pageURL.getPath() + " HTTP/1.1\r\n"); 
     out.print("Host: " + pageURL.getHost() + "\r\n"); 
     out.print("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0\r\n"); 
     out.print("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"); 
     out.print("Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2\r\n"); 
     out.print("\r\n"); 
     out.flush(); 

最重要的是檢查生成的文件。

+0

我也使用BufferedInputStream,但沒有成功 – Ali

+0

,這將不會在read()方法的工作方式上有所不同。 – jtahlborn