Java通过套接字发送文件

时间:2011-04-12 13:31:22

标签: java sockets

我想通过套接字发送文件以及其他一些信息。我使用以下代码

 public void receiveFile(Socket socket,int filesize,String filename) throws IOException
{
    //after receiving file send ack
    System.out.println("waiting ");
 // int filesize=70; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
System.out.println("Connecting...");

// receive file
byte [] mybytearray  = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("recv..."+mybytearray.length);
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   System.out.println(bytesRead);
   if(bytesRead > 0) current += bytesRead;
} while(bytesRead > 0);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
System.out.println(" File received");
}

收到文件后,我必须收到一些其他字符串。但是当我尝试读取输入流时,我正在获取文件的内容。如何从输入流中刷新文件的内容。

BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(
                webServerSocket.getInputStream()));

receiveFile(webServerSocket,filesize,filename);
    while(true)
    {
        msg = inFromServer.readLine(); //here i receive the contents of the file again
     System.out.println(msg);
    }

2 个答案:

答案 0 :(得分:3)

将套接字的inputstream传递给receivefile-method,而不是套接字本身:

InputStream is = webServerSocket.getInputStream();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(is));

receiveFile(webServerSocket,filesize,filename);

我相信问题在于,您在同一时间点(在实际读取任何数据之前)有两个来自同一套接字的输入流。它们指向相同的流,但是从一个流中读取也不会移动另一个流,因此在从inputstreamBA读取之后,一个标记在位置15(例如),而inpustream A仍然处于poisition 0,在流的开头。

(EDIT :) 当然,你必须在receiveFile方法中使用inputstream而不是从套接字中获取一个。另一种解决方案是在调用接收文件后从套接字获取输入流,如

receiveFile(webServerSocket,filesize,filename);

BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(webServerSocket.getInputStream()));

答案 1 :(得分:1)

通过阅读文件完成,您将阅读整个文件。如果您仍在获取文件的内容,则表示尚未阅读整个文件。