简体   繁体   中英

Can't write file to zip

I try to put some file fileNamePath in zip archive (arguments are D:\\text.txt D:\\archive.zip):

  public static void main(String[] args) throws IOException {
    if (args.length==0) return;

    String fileNamePath = args[0];
    String zipPath = args[1];

    FileOutputStream outputStream = new FileOutputStream(zipPath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));

    File file = new File(fileNamePath);
    Files.copy(file.toPath(),zipOutputStream);

    zipOutputStream.closeEntry();
    zipOutputStream.close();

}

Archive is created but i don't see any file in it. Why?

That code is working perfectly:

zip.java

import java.io.*;
import java.nio.file.*;
import java.util.zip.*;

public class zip
{
public static void main(String[] args) throws IOException {
    if (args.length==0) return;

    String fileNamePath = args[0];
    String zipPath = args[1];

    FileOutputStream outputStream = new FileOutputStream(zipPath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));

    File file = new File(fileNamePath);
    Files.copy(file.toPath(),zipOutputStream);

    zipOutputStream.closeEntry();
    zipOutputStream.close();

}
}

I have compiled it under Debian 9 Stretch, OpenJDK 8

I have then created a sample txt file:

hello.txt

Hello World

I then compiled it:

javac zip.java

And finally run it:

java zip hello.txt hello.zip

I extract the .zip and open up hello.txt, returning Hello World

May it be that you have no permissions to read/write D:\\ ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM