【问题标题】:FileOutputStream zip file open ERROR: "File cannot be opened as an archive"FileOutputStream zip 文件打开错误:“文件无法作为存档打开”
【发布时间】:2014-04-25 18:09:30
【问题描述】:

我正在尝试从字节数组创建“.zip”文件,但每次我尝试打开它时都会出现给出的错误。代码如下:

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.PrintWriter;

public class ReadTxtFile {

public static void BinFileContToBinArr(String path) throws Throwable{
    BufferedReader inputStream = null;
    PrintWriter outputStream = null;

    try{
        String el = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        inputStream = new BufferedReader(new FileReader(path));
        FileOutputStream  fos = new FileOutputStream("D:/texttNE22W.zip");
        while((el=inputStream.readLine()) != null){
            baos.write(el.getBytes());
        }
        byte[] b = baos.toByteArray();
        for(int i = 0; i<b.length; i++){
            System.out.print((char)b[i] + " ");
        } 
        fos.write(b);           
    } 
    finally{
        if (inputStream!=null){
            inputStream.close();
        }
        if(outputStream!=null){
            outputStream.close();
        }           
    }
}

public static void main(String[] args) throws Throwable {
    String path = "D:/text.txt";
    BinFileContToBinArr(path);

}
}

我进行了研究,但没有找到解决方案。另外,我尝试创建一个“.txt”文件并且它可以工作。唯一的问题是在创建“.zip”时。

先谢谢你!顺便说一句,如果有人以前遇到过这个问题,如果你愿意,请随时投票或给我留言,因为如果这是一个常见的错误,我很感兴趣。

【问题讨论】:

    标签: java zip fileoutputstream bytearrayoutputstream


    【解决方案1】:

    您需要使用ZipOutputStream 而不是 FileOutputStream。

    【讨论】:

    • 谢谢!但是,在我正在学习的书中,它说要使用 FileOutputStream,我对此解决方案很感兴趣。
    • 所以这本书要求你手动实现压缩?您需要复制 ZipOutputStream 的功能而不使用它吗?您需要编写 Zip 算法的实现吗?这不是很简单,你可能想在这里开始你的研究:en.wikipedia.org/wiki/Zip_%28file_format%29
    • 嗯,是的。谢谢,我一定会从这里开始... :)
    猜你喜欢
    • 2016-05-20
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2016-04-23
    相关资源
    最近更新 更多