编辑*
我已经在客户端服务器上成功操作。现在我正在两个模拟器之间进行文件传输。文件确实在模拟器之间传输了,但我注意到接收到的文件大小不同于原始文件。例如,A.jpg的大小为900KB,但是接收到的文件大小小于900KB。我检查了文件传输大小,并发现在传输时有一些数据(字节)丢失了。这是怎么发生的?
以下是代码:
客户端(发送文件)
以下是代码:
客户端(发送文件)
File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = new FileInputStream(myFile);
OutputStream os = socket.getOutputStream();
int filesize = (int) myFile.length();
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
//Log display exact the file size
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
Log.d("Client", "Client sent message");
socket.close();
服务器(接收文件)
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/Pictures/B.jpg");
@SuppressWarnings("resource")
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = clientSocket.getInputStream();
byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1)
{
bos.write(aByte, 0, bytesRead);
//Log display few parts the file size is less than 1024. I total up, the lost size caused the file received is incomplete
System.out.println("SO sendFile" + bytesRead);
}
clientSocket.close();
*编辑2
我在谷歌上搜索的时候发现,.read(buffer)不能保证读取整个文件的字节大小。因此,接收到的文件总是会丢失一些字节(比如空格、空字符)。为了解决这个问题,先发送文件大小通知接收方,然后才开始传输文件。