Java 套接字文件传输:接收器卡在从缓冲区读取/写入存储器中
发送方文件似乎工作得很好,在“outputstream刷新”之前,我会收到所有日志消息。 在接收方,在代码到达while循环之前,一切似乎都进行得很顺利:我得到的最后一条日志消息总是“试图将inputstream读入缓冲区并将文件写入目标”,而不是“file received”和以下消息。奇怪的是:我收到了测试文件并可以打开它(虽然需要几秒钟——不知道这是否是android的典型情况)。 有没有线索说明为什么代码会卡在while循环中? 第二个问题:这是我的第一个Android/Java应用程序。这个代码可以通过套接字发送和接收文件吗?即使文件变得更大(高达>100MB) 提前谢谢 即Java 套接字文件传输:接收器卡在从缓冲区读取/写入存储器中,java,android,sockets,inputstream,file-transfer,Java,Android,Sockets,Inputstream,File Transfer,发送方文件似乎工作得很好,在“outputstream刷新”之前,我会收到所有日志消息。 在接收方,在代码到达while循环之前,一切似乎都进行得很顺利:我得到的最后一条日志消息总是“试图将inputstream读入缓冲区并将文件写入目标”,而不是“file received”和以下消息。奇怪的是:我收到了测试文件并可以打开它(虽然需要几秒钟——不知道这是否是android的典型情况)。 有没有线索说明为什么代码会卡在while循环中? 第二个问题:这是我的第一个Android/Java应用程序
为.read(buffer)
仅当连接的另一端正常关闭(或在出错时引发异常)时才会返回零,因此您缺少的是发送端的套接字.close()
os.flush()
在这里是不够的,因为TCP不知道您何时发送完数据
static void sendFile(Socket socket, File file) throws IOException {
File testFile = new File( Environment.getExternalStorageDirectory().toString()+"/DCIM/Camera/Test.jpg");
byte [] buffer = new byte[(int)testFile.length()];
FileInputStream fis = new FileInputStream(testFile);
BufferedInputStream bis = new BufferedInputStream(fis);
Log.d(DebugTag, "Trying to read testFile from storage into buffer");
bis.read(buffer,0,buffer.length);
Log.d(DebugTag, "Read testFile into buffer");
OutputStream os = socket.getOutputStream();
Log.d(DebugTag, "Trying to write testFile from buffer into output stream");
os.write(buffer, 0, buffer.length);
Log.d(DebugTag, "Wrote testFile from buffer into output stream");
os.flush();
Log.d(DebugTag, "Outputstream flushed");
}
static void receiveFile(Socket socket) throws IOException {
InputStream is = socket.getInputStream();
String receivedFileDirectory = Environment.getExternalStorageDirectory().toString()+"/Pictures/receivedFile.jpg";
File receivedFile = new File(receivedFileDirectory);
//check if directory exists, otherwise create it
if (receivedFile.exists()) {
Log.d(DebugTag, "Filename at destination already exists");
} else if (!receivedFile.exists()) {
Log.d(DebugTag, "Filename at destination does not exist, trying to create it!");
receivedFile.createNewFile();
Log.d(DebugTag, "Created file!");
}
Log.d(DebugTag, "Preparing file reception. Destination:"+receivedFileDirectory);
OutputStream os = new FileOutputStream(receivedFileDirectory);
Log.d(DebugTag, "established outputstream to file directory");
byte[] buffer = new byte[2048];
int length;
Log.d(DebugTag, "Trying to read inputstream into buffer and write file to destination");
while ((length = is.read(buffer)) >0 ) {
os.write(buffer,0,length);
}
Log.d(DebugTag, "File received.");
os.flush();
os.close();
is.close();
Log.d(DebugTag, "Closed in and out streams");
}