java 如何将 zip 文件读取为字节数组,然后将字节数组转换回 zip 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16166830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:05:21  来源:igfitidea点击:

How to read zip file as byte array and then convert the byte array to back to zip file?

javazipbytearray

提问by Laishram Pilot

I have tried using this code for converting a ZIP file to a byte array:

我曾尝试使用此代码将 ZIP 文件转换为字节数组:

private static byte[] readZipFile(String zipFnm)
// read in fnm, returning it as a single string
{

  FileInputStream fileInputStream=null;

  File file = new File(zipFnm);

  byte[] bFile = new byte[(int) file.length()];

  try{
    //convert file into array of bytes
    fileInputStream = new FileInputStream(zipFnm);
    fileInputStream.read(bFile);
    fileInputStream.close();
  }catch(Exception e){
    e.printStackTrace();
  }
  return bFile;
}  

and this code for converting the byte array to back to ZIP, by calling writeByteToZip(fnm + ".zip");

以及用于将字节数组转换回 ZIP 的代码,通过调用 writeByteToZip(fnm + ".zip");

private static String writeByteToZip(String outFnm)
{
  try {
    FileOutputStream fileOuputStream = new FileOutputStream(outFnm); 
    fileOuputStream.write(bFile);
    fileOuputStream.close();            

  } catch ( IOException iox ){
    iox.printStackTrace();
  }
  return outFnm;
}  // end of writeByteToZip()

What am I doing wrong? I get correct byte length of zip using

我究竟做错了什么?我使用正确的 zip 字节长度

byte[] bzip = readZipFile(zipFnm);

int totalLen1 = bzip.length;
System.out.println("Total byte length of zip: " + totalLen1);

All I get is a zero size zip file and run time error in Netbeans as:

我得到的只是一个零大小的 zip 文件和 Netbeans 中的运行时错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.io.FileOutputStream.write(FileOutputStream.java:305)
    at steg.Steg.writeByteToZip(Steg.java:402)
    at steg.Steg.save(Steg.java:292)
    at steg.frame1.jButton2ActionPerformed(frame1.java:349)
    at steg.frame1.access0(frame1.java:24)
    at steg.frame1.actionPerformed(frame1.java:172)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2713)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
    at java.awt.EventQueue.access
byte[] bFile = new byte[(int) file.length()];
0(EventQueue.java:101) at java.awt.EventQueue.run(EventQueue.java:666) at java.awt.EventQueue.run(EventQueue.java:664) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue.run(EventQueue.java:680) at java.awt.EventQueue.run(EventQueue.java:678) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:677) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105) at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

回答by Duncan Jones

The stacktrace you've provided will be caused because bFileis null.

您提供的堆栈跟踪将导致因为bFile为空。

The cause is likely to be the following line in your readZipFilemethod:

原因可能是您的readZipFile方法中的以下行:

bFile = new byte[file.length()];

Here you are assigning to a localvariable, rather than your class field. Try replacing that line with:

在这里,您将分配给一个局部变量,而不是您的类字段。尝试用以下内容替换该行:

FileInputStream fileInputStream = null;
try {
  fileInputStream = new //...
} finally {
  if (fileInputStream != null) {
    fileInputStream.close();
  }
}


Your code also demonstrates poor resource handling. Either use existing library methods to do your reading (e.g. commons-ioor Java 7 Files) or write code such as:

您的代码还展示了糟糕的资源处理。要么使用现有的库方法来阅读(例如commons-io或 Java 7 Files)或编写代码,例如:

try (FileInputStream fileInputStream = new FileInputStream(zipFnm)) {
  // Use your stream
}

If you have Java 7, you can use try-with-resources:

如果你有 Java 7,你可以使用 try-with-resources:

public byte[] readXMLFile(){
        File file = new File("a.xml");

        byte[] b = new byte[(int) file.length()];
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(b);
            fileInputStream.close();
        }catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
            e.printStackTrace();
        }catch (IOException e1) {
            System.out.println("Error Reading The File.");
            e1.printStackTrace();
        }
        return b;
    }

回答by Aaron Digulla

The problem is probably the variable bFilein writeByteToZip(). Make sure it is not null.

问题可能出bFilewriteByteToZip(). 确保它不是null

In the future, when you post code which throws an exception, mark the line where the exception happens with a comment (// <-- NullPointerException here)

将来,当您发布引发异常的代码时,请用注释 ( // <-- NullPointerException here)标记发生异常的行

回答by Vithushan

I didnt check your code. But i was working with such requirement. SO felt like sharing my code.

我没有检查你的代码。但我正在处理这样的要求。所以感觉想分享我的代码。

To read zip file and convert to byte array:

读取 zip 文件并转换为字节数组:

public void writeXMLFile(byte[] fileContent){
        try {
            FileOutputStream fos = new FileOutputStream("abc.xml");

            fos.write(fileContent);
            fos.close();
        }catch(FileNotFoundException ex){
            System.out.println("FileNotFoundException : " + ex);
        }catch(IOException ioe)  {
            System.out.println("IOException : " + ioe);
        }
    }

To write to zip file from byte array:

从字节数组写入 zip 文件:

static byte[] readAllBytes(Path path)
static Path write(Path path, byte[] bytes, OpenOption... options)

Hope this helps.

希望这可以帮助。

回答by Ivan Senic

As already said the file probably does not exist.

如前所述,该文件可能不存在。

However, I just wanted to mention out the utility in Java 7 you can use. Filesclass offers:

但是,我只想提一下您可以使用的 Java 7 中的实用程序。Files课程优惠:

##代码##

Seams like exactly what you need. It does not matter if the file is Zip or not, simply you can get the bytes easily and then use them to write them to some other file. Note that Path in Java 7 is representing the path to the file in question.

接缝正是您所需要的。文件是否为 Zip 并不重要,您可以轻松获取字节,然后使用它们将它们写入其他文件。请注意,Java 7 中的 Path 表示相关文件的路径。