1

I have a ZIP file and when I convert it into byte array and encode it, I am unable to print the encoded format without writing it into file. Could anyone help in solving this issue?

My code is

        InputStream is = null;  
        OutputStream os = null; 
        is = new FileInputStream("C:/Users/DarkHorse/Desktop/WebServicesTesting/PolicyCredit.zip");  
        os = new FileOutputStream("D:/EclipseTestingFolder/EncodedFile1.txt");  
        int bytesRead = 0;  
        int chunkSize = 10000000;  
        byte[] chunk = new byte[chunkSize];  
        while ((bytesRead = is.read(chunk)) > 0) 
        {  
         byte[] ba = new byte[bytesRead]; 
         for(int i=0;i<ba.length;i++)
                {
                    ba[i] = chunk[i];                       
                } 
             byte[] encStr = Base64.encodeBase64(ba);

             os.write(encStr);            
         } 

        os.close();
        is.close();
}

My Output in the file is

UEsDBBQAAAAIANGL/UboGxdAAQUAAK0WAAAQAAAAUG9saWN5Q3JlZGl0LnhtbJVY3Y6rNhC+r9R34AlqSPankSwkdtNskbLZKOk5Va8QC95d6wRIDZyeffszxgSMGUPKFcx8M/b8egwN87IWcZ6waF+cePLp//qLAw/d8BOL/mRxykRL6sk89T1KLq8adx1XLHp5i55YzkRc8SL3F6534y69O0oQpia6K6LiLTqwpBBpKdUPCRq

But when I am trying to print it on the screen, I am getting in this way

8569115686666816565656573657871764785981117112010065658185656575488765656581656565658571571159787785381517410890711084876110104116987486895189541147810467431145782515265108113838097110107831191071001167811510798769075791075386975681675753100541198273689012110110210211512212010383777185807570991205677479856101103119785655738799905411997704399101807611247471137665119471005666797647109821201211078276

paulsm4
  • 114,292
  • 17
  • 138
  • 190
sailakshmi
  • 25
  • 8

3 Answers3

1

You need to create a string representation of Base 64 encoded data.

System.out.println( new String(encStr, Charset.forName("UTF-8")));

Here are some other examples Base 64 Print Question

String Class

Community
  • 1
  • 1
Pumphouse
  • 2,013
  • 17
  • 26
1

Assuming your result array byte[] encStr = Base64.encodeBase64(ba) is actually the encoded string, try the following:

System.out.println(new String(bytes, Charset.defaultCharset());
Amila
  • 5,195
  • 1
  • 27
  • 46
1

If you are using JDK 7 you can use Files.readAllBytes(path)

Your code would be much simpler like below:

        Path path = Paths.get("C:/Users/DarkHorse/Desktop/WebServicesTesting/PolicyCredit.zip");
        byte[] data = Files.readAllBytes(path);
        byte[] encStr = Base64.encodeBase64(data);
        System.out.println( new String(encStr));

Your will be able to print on console.

Nitesh Virani
  • 1,688
  • 4
  • 25
  • 41