读取zip文件需要获取纯文本而不是二进制流

时间:2014-07-29 05:31:58

标签: java

我已经将二进制流写入zip文件。当我解压缩时,我看到了二进制字符。 请帮我说明如何获取纯文本?

读取方法 - 问题我需要获取纯文本我保存而不是二进制流

 public static void readzipBytes(String filePath){
    try {
          ZipFile zf = new ZipFile(filePath);
          Enumeration entries = zf.entries();


          while (entries.hasMoreElements()) {
            ZipEntry ze = (ZipEntry) entries.nextElement();



              long size = ze.getSize();
              if (size > 0) {
                System.out.println("Length is " + size);
                BufferedReader br = new BufferedReader(
                    new InputStreamReader(zf.getInputStream(ze)));
                String line;
                while ((line = br.readLine()) != null) {
                  System.out.println(line);

                  byte[] bytearray =  line.getBytes("UTF-8");
                  System.out.println(">>>>>>>>>>>>>>>>>>>>>>>"+bytearray.length);
                  for(int o=0; o<bytearray.length; o++){
                    System.out.println("SSS=="+bytearray[o]);

                }

                  String str = new String(bytearray);
                }
                br.close();
              }

          }
        } catch (IOException e) {
          e.printStackTrace();
        }
}

保存方法

 public static byte[] savezipBytesWithWriter(String filename, String message) throws IOException {
        byte[] input = message.getBytes();
        System.out.println("intput length"+input.length);
        File f = new File("C:\\tmp\\t113.zip");
        OutputStream outputStream = new FileOutputStream (f); 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        Writer writer = new OutputStreamWriter(baos);
        writer.write(message);


        ZipEntry entry = new ZipEntry(filename);
        entry.setSize(input.length);
        zos.putNextEntry(entry);

        System.out.println("baos barray length"+baos.toByteArray().length);           
        zos.write(baos.toByteArray());
        zos.closeEntry();
        zos.close();
        System.out.println(baos.toString());
        baos.writeTo(outputStream);
        return baos.toByteArray();
    }

保存方法

1 个答案:

答案 0 :(得分:1)

ZipOutputStream zos = new ZipOutputStream(baos);;

您要在ZipOutputStream

周围构建ByteArrayOutputStream.
Writer writer = new OutputStreamWriter(baos);

您要在同一Writer

周围构建ByteArrayOutputStream.
writer.write(message);

您在此处直接向ByteArrayOutputStream.

撰写邮件
zos.write(baos.toByteArray());

在这里,您要将ByteArrayOutputStream所包含的ZipOutputStream字节数组的内容写入ZipOutputStream.

基本上这段代码没有意义。

尝试将邮件直接写入ZipOutputStream.您根本不需要ByteArrayOutputStream。只需在其周围构建一个FileOutputStream, ZipOutputStream,并围绕该Writer构建一个{{1}}。