使用命令行在Windows中的zip文件夹

12r*_*rad 3 java windows command

我正在编写一个需要压缩文件的程序.这将在Linux和Windows机器上运行.它在Linux中运行得很好,但我无法在Windows中完成任何操作.要发送命令,我使用的是apache-net项目.我也尝试过使用Runtime().exec,但是它没有用.有人可以建议吗?

CommandLine cmdLine = new CommandLine("zip");
     cmdLine.addArgument("-r");
     cmdLine.addArgument("documents.zip");
     cmdLine.addArgument("documents");
     DefaultExecutor exec = new DefaultExecutor();
     ExecuteWatchdog dog = new ExecuteWatchdog(60*1000);
     exec.setWorkingDirectory(new File("."));
     exec.setWatchdog(dog);
    int check =-1;
    try {
        check = exec.execute(cmdLine);
    } catch (ExecuteException e) {

    } catch (IOException e) {
    }
Run Code Online (Sandbox Code Playgroud)

pha*_*ers 6

Java在java.util.zip.*中提供了自己的压缩库,支持.zip格式.可以在此处找到拉链文件夹的示例.这是一个适用于单个文件的快速示例.使用本机Java的好处是它可以在多个操作系统上运行,并且不依赖于安装特定的二进制文件.

  public static void zip(String origFileName) {
    try {
      String zipName=origFileName + ".zip";
      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
      byte[] data = new byte[1000]; 
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(origFileName));
      int count;
      out.putNextEntry(new ZipEntry(origFileName));
      while((count = in.read(data,0,1000)) != -1) {  
        out.write(data, 0, count);
      }
      in.close();
      out.flush();
      out.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Run Code Online (Sandbox Code Playgroud)