2017-02-10 28 views
0

我有以下代碼上傳文件從客戶端到服務器TCP,但是當我嘗試打開手動文件是空的爲什麼好的重量.. 我看了很多帖子stackOverflow但沒有任何改變 THX (對不起我的英文不好)
服務器:BufferedOuputStream使空白文件

ThreadServer擴展公共Thread類{

private Socket soc; 
private FileOutputStream fos; 
private BufferedOutputStream bos; 
private InputStream in; 

public ThreadServer (Socket soc) { 
    this.soc = soc; 
} 

public void run(){ 
    try { 
     fos = new FileOutputStream("C:/Users/erwan/workspace/Word/server/text.txt"); 
    } catch (FileNotFoundException e1) { 
     e1.printStackTrace(); 
    } 
    bos = new BufferedOutputStream(fos); 
    byte[] buffer = new byte[1024]; 
    try { 
     in = soc.getInputStream(); 
     int count = 0; 
     while((count= in.read(buffer, 0 , buffer.length)) != -1) { 
      System.out.println(count+" octets received...");     
      bos.write(buffer); 
     } 
     bos.flush(); 
     bos.close(); 
     in.close(); 
     soc.close(); 
     System.out.println("File sent succesfully!"); 
    }catch(IOException e){ 
     e.printStackTrace(); 
     System.out.println("Une erreur est survenu"); 
    } 
} 

}

客戶端:

public class Client { 
private static Socket as; 
private static FileInputStream fis; 
private static BufferedInputStream bis; 
private static OutputStream out; 
public static void main(String[] args){ 
    as = null; 
    try{ 
     as = new Socket(InetAddress.getLocalHost(),4020); 

     File f = new File (args[0]); 
     byte [] buffer = new byte [(int) f.length()]; 
     fis = new FileInputStream(f); 
     setBis(new BufferedInputStream(fis)); 
     out = as.getOutputStream(); 
     System.out.println("uploading..."); 
     out.write(buffer,0,buffer.length); 
     out.flush(); 
     out.close(); 
     System.out.println("the file is uploaded."); 
     as.close(); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 

}

回答

0

在客戶機緩衝似乎不與數據填充。它被初始化爲具有文件長度的字節數組,但是在輸入流上沒有讀取方法調用。爲了測試fis.read(緩衝區),可能會很快將一些數據存入緩衝區。請記住,讀取不能保證填充整個緩衝區。特別是如果你的文件包含零,那麼缺乏將實際數據讀入(客戶端的)緩衝區是可能的罪魁禍首。

除此之外,服務器代碼還假定read方法完全填充緩衝區,所以write方法調用應指定長度(count)。所以把bos.write(buffer)改成bos.write(bos,0,count)。這可能會在文件末尾變得很明顯(如果文件長度超過1024個字節),因爲文件末尾將成爲前一個塊中某些數據的重複。

+0

我真的不明白爲什麼fis.read(buffer,0,buffer.lenght)解決了這個問題,但真的非常感謝你回答:)如果你能再次解釋我的dos是如何工作的? thx –

+0

是的。這並不複雜。你做了一個新的字節[(int)f.length()]。所做的是分配一個存儲區域來存儲f.length()字節。它不會將任何數據放入這些內存字節中。在大多數情況下,數組將被jvm初始化爲0個字節(二進制零,因此經常在編輯器中顯示爲奇怪的字符)。爲了將您的輸入文件中的數據動態地放入新創建的數組中,您需要執行fis.read。 –