3

我正在编写代码以创建 txt 文件,并且在完全写入该 txt 文件后意味着完全关闭 txt 文件而不是压缩该文件。但是,我不知道为什么,它不会等到文件关闭之前文件关闭它压缩它..请帮助我

这是我的代码:

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class zipfile {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        BufferedWriter bfAllBWPownmanmainfest = null;
        String mainfest = "file\\" + "fileforzip" + ".txt";
        bfAllBWPownmanmainfest = new BufferedWriter(new FileWriter(mainfest));

        bfAllBWPownmanmainfest.write("jdshsdksdkhdshksd\n");
        bfAllBWPownmanmainfest.write("jdshsdksdkhsdfsdfsddshksd\n");
        bfAllBWPownmanmainfest.write("jdshsdksdsdfdskhdshksd\n");
        bfAllBWPownmanmainfest.write("jdshsdksddsfdskhdshksd\n");
        bfAllBWPownmanmainfest.write("jdshsdksddsfdskhdshksd\n");
        bfAllBWPownmanmainfest.write("jdshsdksdsdfdskhdshksd\n");
        bfAllBWPownmanmainfest.write("jdshsdksddsfsdkhdshksd\n");

        bfAllBWPownmanmainfest.flush();
        bfAllBWPownmanmainfest.close();

        //After close file than zip that!! please help me Thanks

        FileOutputStream fout = new FileOutputStream("test.zip");
        ZipOutputStream zout = new ZipOutputStream(fout);

        ZipEntry ze = new ZipEntry(mainfest);
        zout.putNextEntry(ze);
        zout.closeEntry();
        zout.close();

    }

}

关闭后 bfAllBWPownmanmainfest.close(); 比压缩它,我怎么能做到这一点,请帮助我提前谢谢!它创建空的zip文件,它没有等到文件完全关闭!请帮我!!谢谢!!

4

2 回答 2

3

您已经创建了一个ZipEntry,但实际上并未将任何字节写入输出 zip 文件。您需要从InputStream您的文件中读取并写入您ZipOutputStreamputNextEntry(ZipEntry).

FileInputStream in = new FileInputStream(mainfest);
byte[] bytes = new byte[1024];
int count;

FileOutputStream fout = new FileOutputStream("test.zip");
ZipOutputStream zout = new ZipOutputStream(fout);

ZipEntry ze = new ZipEntry(mainfest); // this is the name as it will appear if you opened the zip file with WinZip or some other zip manager
zout.putNextEntry(ze);

while ((count = in.read(bytes)) > 0) {
    zout.write(bytes, 0, count);
}

zout.closeEntry();
zout.close();
于 2013-08-28T19:47:29.630 回答
0

您不需要。在声明ZipEntry之前bfAllBWPownmanmainfest.close();尝试此代码。

    ZipOutputStream zout = new ZipOutputStream(fout);
    int size = 0;
    byte[] b = new byte[1000];
    while ((size = bfAllBWPownmanmainfest.read(b)) > 0) {
       zout.write(b, 0, size);
    }
    zout.close();
    bfAllBWPownmanmainfest.close();
于 2013-08-28T19:48:28.240 回答