使用 Java 将文件压缩到特定文件夹中

Zip files in particular folder using Java

我只是想要一个特定文件夹中的 7Z 文件(仅 .pdf 和 .txt 文件)的代码,并将其放在同一文件夹中。

我可以输入的是文件夹位置。

有人可以帮忙吗?

是否可以在 Java 或 Java 脚本中完成?

我是初学者..需要帮助..提前致谢

我不知道你到底想要什么,但以下内容可能会有所帮助:

/*
 * Search for files in the folder and copy
 * them into a zip file.
 */

//Your files
File folder = new File("C:\Java\Example\");
File destination = new File("C:\Java\ZipFile.zip");

//Output streams for writing the zip file
FileOutputStream fos = new FileOutputStream(destination);
ZipOutputStream zos = new ZipOutputStream(fos);

//Search for files in the directory, ignore sub-directories
for(File file : folder.listFiles()) {
    if(file.isDirectoy())
        continue;

    //Create a zip entry and set the ZipOutputStream to
    //write a new file inside the zip file.
    ZipEntry entry = new ZipEntry(file.getName());
    zos.putNextEntry(entry);

    //Open a FileInputStream to read from the current file
    FileInputStream fis = new FileInputStream(file);

    //Stream the contents of the file directly
    //to the ZipOutputStream
    int length;
    byte[] buffer = new byte[1024];
    while((length = fis.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }

    //Close the input stream and the zip
    //entry for the next file
    fis.close();
    zos.closeEntry();
}

//Close the ZipOutputStream
zos.close();

如果您有一个名为 Example 的文件夹,所有 文件 将被复制到一个 zip 文件中。