我从服务器端客户端传送图像文件,在读取图像文件我得到这个问题 [英] I am transferring image file from server side to client, while reading image file i got this issue
问题描述
我使用以下code从套接字读取图像文件。它从服务器读取的所有字节,因为服务器和Android机文件的大小相同。当我打开这个文件,它不会打开文件并生成错误是损坏或文件太大。
公共位图fileReceived(InputStream为)
抛出FileNotFoundException异常,IOException异常{ 位图位图= NULL;
字符串BASEDIR = Environment.getExternalStorageDirectory()getAbsolutePath()。
字符串文件名=a.png;
字符串imageInSD = BASEDIR +文件分割符+文件名;
的System.out.println(imageInSD);
如果(是!= NULL){
FOS的FileOutputStream = NULL;
BOS的BufferedOutputStream = NULL;
尝试{ FOS =新的FileOutputStream(imageInSD);
BOS =新的BufferedOutputStream(FOS);
字节[] = aByte新的字节[1024];
INT读取动作; 而(真){
读取动作= is.read(aByte); bos.write(aByte,0,读取动作);
如果(is.available()== 0)
打破;
} bos.flush();
bos.close();
// is.reset(); //这里给出错误即--- SkImageDe codeR ::厂返回null
位= BitmapFactory.de codeFILE(imageInSD); }赶上(IOException异常前){
//做异常处理
Log.i(IMSERVICE,异常);
}
} 返回位图;
}
不要使用的 用()
这一点,就不能可靠地工作!
该文档的状态:
[用()返回可以读取的字节数的估算 [...]这是从来没有正确的使用这个方法的返回值来分配意在缓冲持有此流的所有数据。
块引用>做这样:
,而((读取动作= is.read(aByte))0){
bos.write(aByte,0,读取动作);
}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. 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!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.
Do it like:
while ( (bytesRead = is.read(aByte)) > 0 ) { bos.write(aByte, 0, bytesRead); }
这篇关于我从服务器端客户端传送图像文件,在读取图像文件我得到这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!