我正在编写一些代码来创建一个 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 文件,它没有等到文件完全关闭!
最佳答案
您已经创建了一个 ZipEntry
,但实际上还没有将任何字节写入输出 zip 文件。您需要从文件的 InputStream
读取并在 putNextEntry(ZipEntry)
之后写入您的 ZipOutputStream
。
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();
关于完全写入文件后压缩文件的Java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496859/