【问题标题】:How do I create a zip file one folder up from the present working directory with NIO?如何使用 NIO 从当前工作目录向上一个文件夹创建一个 zip 文件?
【发布时间】:2014-08-06 17:16:04
【问题描述】:

我在使用 URI 类时遇到问题。

我可以在 c:\ 中创建一个 zip 文件,代码如下:

// Properties for archive file we're creating
Map<String, String> archiveProperties = new HashMap<>(); 
archiveProperties.put("create", "true");
archiveProperties.put("encoding", "UTF-8");        
URI archiveLocation = URI.create("jar:file:/" + "my.zip");

// Create archive
FileSystem archive = FileSystems.newFileSystem(archiveLocation, archiveProperties);

但如果您愿意的话,我真的希望将 zip 文件从当前工作目录中创建一个目录。我尝试了很多东西,包括:

// Properties for archive file we're creating
Map<String, String> archiveProperties = new HashMap<>(); 
archiveProperties.put("create", "true");
archiveProperties.put("encoding", "UTF-8");        
URI archiveLocation = URI.create("jar:file:../" + "my.zip");

// Create archive
FileSystem archive = FileSystems.newFileSystem(archiveLocation, archiveProperties);

但我要么得到一个异常,在这种情况下 URI 不是分层的,要么它继续在 c:\

中创建

【问题讨论】:

    标签: java zip uri nio


    【解决方案1】:

    我终于想出了一个解决方案,虽然不是很漂亮:

    // Properties for archive file we're creating
    Map<String, String> archiveProperties = new HashMap<>(); 
    archiveProperties.put("create", "true");
    archiveProperties.put("encoding", "UTF-8");        
    
    String filePathName = System.getProperty("user.dir") + FILE_SEPARATOR + ".." + FILE_SEPARATOR + "myfile.zip";
    filePathName = filePathName.replace('\\','/');
    filePathName = filePathName.replaceAll(" ", "%20");
    URI archiveLocation = URI.create("jar:file:///" + filePathName);
    
    // Create archive
    FileSystem archive = FileSystems.newFileSystem(archiveLocation, archiveProperties);
    

    注意 FILE_SEPARATOR 来自 System.getProperty(file.separator)

    【讨论】:

      【解决方案2】:

      快速解决方法是使用它

      URI archiveLocation = URI.create("jar:file:///"+new File(".").getAbsolutePath()+"/../my.zip");
      

      【讨论】:

      • 感谢您的建议。我试了一下,遇到了异常。 :-( 线程“main”java.lang.IllegalArgumentException 中的异常:索引 14 处不透明部分中的非法字符:jar:file:///C:\Users\IBM_ADMIN\Documents\Eclipse 工作区 RTC Dev Stream2\bin\./ ../my.zip at java.net.URI.create(URI.java:870)
      • 您只需要更改文件分隔符以匹配您的 Windows 环境,就像您在答案中所做的那样。
      • 谢谢,娜迦。我无法相信这个看似简单的任务是多么困难。
      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 2010-12-09
      • 2021-04-02
      • 2018-08-02
      • 2014-04-16
      相关资源
      最近更新 更多