0

I have Base64 content of an xml file.I want to decode that and save the content of file to a string rather than saving in external file. Can anyone suggest this. Please see the following thing

Base64 Encoded Format

PD94bUeXBlPmVJQSBjaGFuZ2VzPC9GaWxlVHlwZT4NCiAgICA8RmlsZURhdGU+=

File Content

<DATA>
  <Table>
    <LotNo>50700022611201413280</LotNo>
    <FileFrom>CAMS Repository Services Limited</FileFrom>
    <NoOfRec>2</NoOfRec>
    <FileType>eIA partial</FileType>
    <FileDate>26/11/2014 13:28:02</FileDate>
    <FileFromCode>5</FileFromCode>
    <FileToCode>7</FileToCode>
    <FileTypeCode>301</FileTypeCode>
  </Table>
</Data>

I am using following code for this

String outFnm="PD94bUeXBlPmVJQSBjaGFuZ2VzPC9GaWxlVHlwZT4NCiAgICA8RmlsZURhdGU+=";
    byte[] b1=outFnm.getBytes();
        byte[] bFile=Base64.decodeBase64(b1);
        //System.out.println(b1.toString());
            //Integer bFile2=Integer.parseInt(bFile);
        System.out.println(b1);
        System.out.println(bFile.toString());   
        FileOutputStream fos = new FileOutputStream("D:/test.txt");
        fos.write(bFile);
        fos.close();

But I don't want to use a seperate file to store that. I want a string variable which stores the "test.txt" contents.

sailakshmi
  • 25
  • 8
  • Possible duplicate of [Decode Base64 data in Java](https://stackoverflow.com/questions/469695/decode-base64-data-in-java) – Luna Jul 16 '15 at 12:13

2 Answers2

1

If you're using java 8, you can do like

import java.util.Base64;

byte[] decoded = Base64.getDecoder().decode(encoded);
String s = new String(decoded);

Here encoded is the byte[] array of base64 string.

String base64String = "YOUR-BASE64";
byte[] encoded = base64String.getBytes();
The Coder
  • 2,562
  • 5
  • 33
  • 62
0

String has a constructor that takes a byte array. Simply do

String myString = new String(bFile)
Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36