我终于可以弄清楚了!碰巧,客户端(Android)创建了一个用于接收的线程和一个用于写入的线程。因此,当我发送图像时,它是成块发送的,即Android OS会不时暂停写入线程,因此服务器端(Java应用程序)上的inputStream看到图像是成块的。因此,ImageIO.read()
不是成功读取图像而是读取图像的一部分,这就是为什么我得到“ java.lang.IllegalArgumentException:im == null!”的原因,因为仅凭一个块就无法创建任何图像。
除了图像之外,我还向服务器发送了“文件结束”字符串,因此它知道文件何时完成(我想对此有更好的方法,但这是可行的)。在服务器端,在while循环中,我接收所有字节块并将它们全部放在一起,直到接收到“文件末尾”。代码:
Android客户端:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
mBluetoothService.write(b);
mBluetoothService.write("end of file".getBytes());
Java服务器:
byte[] buffer = new byte[1024];
File f = new File("c:/users/temp.jpg");
FileOutputStream fos = new FileOutputStream (f);
int bytes = 0;
boolean eof = false;
while (!eof) {
bytes = inputStream.read(buffer);
int offset = bytes - 11;
byte[] eofByte = new byte[11];
eofByte = Arrays.copyOfRange(buffer, offset, bytes);
String message = new String(eofByte, 0, 11);
if(message.equals("end of file")) {
eof = true;
} else {
fos.write (buffer, 0, bytes);
}
}
fos.close();
希望它能帮助到别人。