开发者

ByteArray To XML file in Android

I am sending a file in byte[] format from web service to android device.

  1. If that file is an XML file i.e. byte[] array then how could i convert it to original XML file.
  2. If that file is an image i.e. byte[] array then how could i convert it to orig开发者_开发技巧inal Image.

I am using android sdk 2.2 on samsung galaxy tab.


Your Webservice should send you some identifier about the file type. whether the byte array is for image or is for general file. then only you can know about which type of file it is. after knowing file type you can convert the byte array into your desired file type. Also you can write to file. If you want to print that xml in logcat you can use

String xmlData = new String(byte[] data); System.out.println(xmlData)

create a file (whether xml or image or anything) if you know the file format

String extension = ".xml"//or ".jpg" or anything
String filename = myfile+extension;
byte[] data = //the byte array which i got from server
File f = new File(givepathOfFile+filename );

        try {
            f.createNewFile();

            // write the bytes in file
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(data );
            fo.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Thanks Deepak


A byte array containing XML already is an XML document. If you want to make it an XML file, then just write the bytes to a file.

The same applies for an image file.

Are you really just asking how to write a byte array as a file?


Here's how to write bytes to a file in Java.

byte[] bytes = ...
FileOutputStream fos = new FileOutputStream("someFile.xml");
try {
    fos.write(bytes);
} finally {
    fos.close();
}

Note that you need to close an opened stream in a finally block or else you risk leaking a file descriptors. If you leak too many file descriptors, later attempts to open files or sockets could start failing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜