2011-05-20 227 views
0

這裏有一個小代碼。這個類運行在兩臺計算機上,一方發送一個文件(send()),另一個接收它(read())。我知道send()的作品,因爲當我運行學校解決方案(它的任務),它可以從我這裏下載文件,但由於某種原因,當我嘗試下載文件創建(由構造函數),但閱讀不寫進入文件。無法通過套接字傳輸文件,java

public class SendFile extends BasicMessage implements Message{ 

private File _file; 

public SendFile(CommandEnum caption){ 
    super(caption); 
} 

public SendFile(String file){ 
    super(CommandEnum.FILE); 
    _file = new File(FMDataManager.instance().getSharedDirectory(),file); 
} 

public void send (DataOutputStream out) throws IOException{ 
    out.writeUTF(_caption.toString()); 
    out.writeLong(_file.length()); 
    FileInputStream fis = new FileInputStream(_file); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    for (int i=0; i<_file.length(); i++) 
     out.write(bis.read()); 
    out.writeUTF(CommandEnum.END.toString()); 
} 

public void read(DataInputStream in) throws IOException{ 
    FileOutputStream fos = new FileOutputStream(_file); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    in.readUTF(); 
    long size = in.readLong(); 
    for (int i=0; i<size; i++) 
     bos.write(in.read()); 
    System.out.println(in.readUTF()); 
} 

} 

有什麼想法嗎?謝謝

回答

0

你必須關閉你的流,以確保它是正確的。在你的特殊情況下,文件內容可能仍然在BufferedOutputStream中。

+0

你可以看到我在這些方法中獲取數據流作爲參數。這個流稍後會在它創建的同一個類中關閉,你是否仍然認爲這可能是問題所在? – yotamoo 2011-05-20 09:32:53

+0

你是對的,謝謝 – yotamoo 2011-05-20 09:49:33