安卓,读取二进制数据并写入文件

0 投票
3 回答
4987 浏览
提问于 2025-04-16 12:01

我正在尝试从服务器读取一个图片文件,下面是我用的代码。它总是进入异常状态。我知道发送的字节数是正确的,因为我在接收时打印出来了。我是这样从Python发送图片文件的:

#open the image file and read it into an object
        imgfile = open (marked_image, 'rb')  
        obj = imgfile.read()

       #get the no of bytes in the image and convert it to a string
        bytes = str(len(obj))


        #send the number of bytes
        self.conn.send( bytes + '\n')




        if self.conn.sendall(obj) == None:
            imgfile.flush()
            imgfile.close()
            print 'Image Sent'
        else:
            print 'Error'

这是安卓部分,这里是我遇到问题的地方。有没有什么好的建议,关于如何接收这个图片并把它写入文件?

//read the number of bytes in the image
       String noOfBytes =  in.readLine();


       Toast.makeText(this, noOfBytes, 5).show();

       byte bytes [] = new byte [Integer.parseInt(noOfBytes)];

       //create a file to store the retrieved image
       File photo = new File(Environment.getExternalStorageDirectory(),  "PostKey.jpg");

       DataInputStream dis = new DataInputStream(link.getInputStream());
       try{


        os =new FileOutputStream(photo);

        byte buf[]=new byte[1024];

        int len;

        while((len=dis.read(buf))>0)
        os.write(buf,0,len);

        Toast.makeText(this, "File recieved", 5).show();

        os.close();
        dis.close();
       }catch(IOException e){

           Toast.makeText(this, "An IO  Error Occured", 5).show();
       }

补充:我还是无法让它正常工作。我已经尝试了很久,所有的努力要么导致文件大小不对,要么就是应用崩溃。我知道在发送之前,文件并没有损坏。根据我的观察,文件肯定是发送成功的,因为Python中的发送方法要么发送所有内容,要么在出错时抛出异常,而到目前为止,它从来没有抛出过异常。所以问题出在客户端。我必须从服务器发送文件,所以我不能使用Brian建议的方法。

3 个回答

0

我不太明白你的代码。你在用 dis.readFully(bytes); 这个方法把 dis 的内容写入你的 byte 数组里。但是之后你并没有对这个数组做任何处理,然后又试图通过一个缓冲区把 dis 的内容写入你的 FileOutputStream

你可以试着把 dis.readFully(bytes); 这一行注释掉。

顺便说一下,我建议把一些信息,比如字节数或者出现异常时,写入日志,而不是弹出提示框。

...
} catch (IOException e) {
    Log.e("MyTagName","Exception caught " + e.toString());
    e.printStackTrace();
}

你可以查看这些链接,里面有关于如何把文件写入SD卡的例子:

1

从服务器获取位图的最佳方法是执行以下操作。

HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet("http://yoururl");

HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();

Bitmap image = BitmapFactory.decodeStream(is);

这样你就能得到你的位图,如果想把它保存到文件里,可以做类似下面的操作。

FileOutputStream fos = new FileOutputStream("yourfilename");
image.compress(CompressFormat.PNG, 1, fos);
fos.close();

你也可以把这两步结合起来,直接写入磁盘。

HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet("http://yoururl");

HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();

FileOutputStream fos = new FileOutputStream("yourfilename");

byte[] buffer = new byte[256];
int read = is.read(buffer);

while(read != -1){
    fos.write(buffer, 0, read);
    read = is.read(buffer);
}

fos.close();
is.close();

希望这对你有帮助;

-1

我在Ubuntu论坛上得到了一个朋友的帮助,解决了这个问题。问题出在读取字节上,它把图片的一部分字节给截断了。解决办法就是直接把整个图片发送过去,不再单独发送字节了。

撰写回答