簡體   English   中英

無法通過套接字傳輸文件,Java

[英]failing to transfer a file through a socket, java

這是一些代碼。 該類在兩台計算機上運行,​​一側發送文件(send()),另一側接收文件(read())。 我知道send()可以工作,因為當我運行學校解決方案(它的作業)時,它可以從我這里下載文件,但是由於某些原因,當我嘗試下載文件時(由構造函數創建),但read沒有寫任何東西到文件中。

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());
}

}

有任何想法嗎? 謝謝

您必須關閉流以確保其正確。 在您的特定情況下,文件內容可能仍在BufferedOutputStream中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM