将ZIP转换为字节数组而不将输出保存到文件

时间:2015-08-06 06:30:22

标签: java

我有一个ZIP文件,当我将其转换为字节数组并对其进行编码时,我无法在不将其编入文件的情况下打印编码格式。 任何人都可以帮忙解决这个问题吗?

我的代码是

        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();
}

文件中的我的输出

  

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

但是当我尝试在屏幕上打印时,我就是这样了

  

8569115686666816565656573657871764785981117112010065658185656575488765656581656565658571571159787785381517410890711084876110104116987486895189541147810467431145782515265108113838097110107831191071001167811510798769075791075386975681675753100541198273689012110110210211512212010383777185807570991205677479856101103119785655738799905411997704399101807611247471137665119471005666797647109821201211078276

3 个答案:

答案 0 :(得分:1)

您需要创建Base 64编码数据的字符串表示形式。

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

以下是其他一些示例Base 64 Print Question

String Class

答案 1 :(得分:1)

假设您的结果数组byte [] encStr = Base64.encodeBase64(ba)实际上是编码字符串,请尝试以下操作:

System.out.println(new String(bytes, Charset.defaultCharset());

答案 2 :(得分:1)

如果您使用 JDK 7 ,则可以使用Files.readAllBytes(path)

您的代码会更简单,如下所示:

        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));

您可以在控制台上打印。