从ZIP文件中获取byte []

时间:2014-10-19 09:55:45

标签: java zip

我需要从* .zip获取一个文件作为字节数组。我这样做

String zipFileLocation = pathToFile;


File file = new File(zipFileLocation);
ZipFile zipfile = new ZipFile(file);

ZipEntry zipentry;

System.out.println("nList of files in zip archive");
int fileNumber = 0;
for (Enumeration<? extends ZipEntry> e = zipfile.entries(); 
e.hasMoreElements(); fileNumber++) {
zipentry = e.nextElement();

if (!zipentry.isDirectory()) {
   System.out.println(fileNumber + "-" + zipentry.getName());
 }
} 

for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements(); ) {
zipentry = e.nextElement();
 if (!zipentry.isDirectory()) {
    fileName  = zipentry.getName();
 InputStream input = zipfile.getInputStream(zipentry);
 BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
 (hash map) nameANDbytes.put(fileName, br.toString().getBytes());
}

让我们说,我得到了

 [B@8f2ef19

但是当我解压缩文件并执行:

String pathToCheckingFile = "path_to_file";
        byte[] b = {};
        try {
        RandomAccessFile f = new RandomAccessFile(pathToCheckingFile, "r");
        b = new byte[(int) f.length()];
        f.read(b);
    }catch(FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e) {
        e.printStackTrace();
    }

        System.out.println(b);

我明白了:

 [B@2cf3d63b

出了什么问题?

此外,如果我多次使用最后一段代码 - 我总是会得到不同的结果。

3 个答案:

答案 0 :(得分:2)

您可以使用以下代码获取字节或字符串:

public static void main(String[] args) throws IOException {
    ZipFile zipFile = new ZipFile("C:/Test/Test.zip");
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()){
        ZipEntry entry = entries.nextElement();
        System.out.println(entry.getName());
        InputStream stream = zipFile.getInputStream(entry);

        //For characters
        //BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        BufferedInputStream reader = new BufferedInputStream(stream);
        //For line reading
        //System.out.println(reader.readLine());
        int byteRead = reader.read();
        while(byteRead != -1) {
            System.out.println(byteRead);
            byteRead = reader.read();
        }

    }
}

您看到的只是每次运行时实例化的对象,toString表示对象哈希码的无符号十六进制表示

答案 1 :(得分:0)

BufferedReader.toString()不会执行任何I / O.如果您想要流的内容,您必须阅读它们。除非您知道该文件是文本,否则BufferedReader不合适。

答案 2 :(得分:0)

首先,我们可以将zip文件转换为简单文件对象。 Apache Commons库IOUtils具有用于执行相同操作的内置功能。<​​/ p>

ZipFile zipFile = new ZipFile(convertMultiPartToFile(file)
byte[] bytes = IOUtils.readAllBytes(zipFile.getInputStream(entry));