Java sending files through sockets
I want to send files as well as some other information through sockets. I am using the following code
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");
}
After receiving the file, I have to receive some other strings. But when I try to read the input stream, I am getting the contents of the file. How to flush the contents of the file from the inputstream.
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);
}
Pass the socket's inputstream to the receivefile-method, instead of the socket itself:
InputStream is = webServerSocket.getInputStream();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(is));
receiveFile(webServerSocket,filesize,filename);
The problem lies, I believe, in the fact that you have two inputstreams from the same socket made at the same point in time (before any data has actually been read). They point to the same stream but reading from one does not move the other as well, thus after reading from inputstreamBA that one is marked in position 15 (for example) while inpustream A is still in poisition 0, at the beginning of the stream.
(EDIT:) Ofcourse, you have to use the inputstream in the receiveFile method instead of getting one from the socket. Another solution would be to get the inputstream from the socket after the call to receive file, as in
receiveFile(webServerSocket,filesize,filename);
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(webServerSocket.getInputStream()));
By reading the file to completion, you will have read the whole file. If you are still getting the contents of the file, you haven't read the whole file.
精彩评论