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

标签 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 文件,它没有等到文件完全关闭!

最佳答案

您已经创建了一个 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/

相关文章:

java - 反射(reflect)通用类

java - 检查套接字发送的对象类型时,服务器未接收到对象

java - 在 File.createTempFile() 上使用 Files.copy() 时出现 FilesAlreadyExistsException

java - Jersey json web 服务客户端实现

java - 如何使用java删除或隐藏Http响应错误

java - 家长是否阻止我保持透明度

java - 将零填充到一位数以形成分钟格式

jvm - 需要服务器 VM 但在 JRE 中不可用。那我需要什么包: JRE, JDK呢?

java - 如何在SOLR中实现 "starts with"搜索?

java - 如何在Eclipse程序中重定向输入和输出