完全写入文件后压缩文件的Java代码

时间:2013-08-28 19:41:16

标签: java

我正在写代码来创建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文件,它没有等到文件完全关闭!! 请帮我!!谢谢!!

2 个答案:

答案 0 :(得分:3)

您已经创建了ZipEntry,但实际上没有将任何字节写入输出zip文件。您需要阅读文件的InputStream并在ZipOutputStream之后写信至putNextEntry(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();

答案 1 :(得分: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();