[英]I am transferring image file from server side to client, while reading image file i got this issue
I am using following code for reading image file from socket. 我正在使用以下代码从套接字读取图像文件。 It reads all the bytes from server because size of file on server and android machine are same. 它从服务器读取所有字节,因为服务器和android机器上的文件大小相同。 When i open this file it does not open the file and generate error that is the file is corrupted or too large. 当我打开此文件时,它不会打开文件并生成错误消息,表明文件已损坏或太大。
public Bitmap fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
System.out.println(imageInSD);
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(imageInSD);
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ( true ) {
bytesRead = is.read(aByte);
bos.write(aByte, 0, bytesRead);
if ( is.available()==0)
break;
}
bos.flush();
bos.close();
// is.reset();
// here it give error i.e --- SkImageDecoder::Factory returned null
bitmap = BitmapFactory.decodeFile(imageInSD);
} catch (IOException ex) {
// Do exception handling
Log.i("IMSERVICE", "exception ");
}
}
return bitmap;
}
Don't use available()
for this, it won't work reliably! 不要为此使用available()
,它将无法可靠地工作!
The docs state: 文档状态:
[ available() ] Returns an estimate of the number of bytes that can be read [...] It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream. [available()]返回可以读取的字节数的估计值 。[...]使用此方法的返回值分配旨在保留此流中所有数据的缓冲区永远是不正确的。
Do it like: 这样做:
while ( (bytesRead = is.read(aByte)) > 0 ) {
bos.write(aByte, 0, bytesRead);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.