Windows上的NIO Files.createTempDirectory导致异常

时间:2016-11-21 22:53:37

标签: java nio

我有一些代码可以在系统的临时文件位置创建一个临时目录:

try {
            Path tempdir = Files.createTempDirectory("tempmm");
            tempdir.toFile().deleteOnExit();
            tempFilename = format("%s/%s.zip", tempdir, meetId);

            // Handle windows
            //tempFilename = tempFilename.replace("\\", "/");

            uri = URI.create("jar:file:" + tempFilename);

            System.out.println("temp file uri = " + uri.toString());

        } catch (IOException e) {
            log.severe(format("Unable to create temporary directory: %s", e.toString()));
    }

try (FileSystem zipfs = FileSystems.newFileSystem(uri, new HashMap<String, String>() {{ put("create", "true"); }})) {

            Path externalMMFile = Paths.get(filePath);
            Path pathInZipfile = zipfs.getPath(externalMMFile.getFileName().toString());

            // copy Meet Manager Database file into the zip file
            Files.copy(externalMMFile,pathInZipfile, StandardCopyOption.REPLACE_EXISTING );
        } catch (IOException e) {
            log.severe("Unable to create zip upload file!");
            System.out.println(e.toString());
            return false;
 }

这是发生的例外:

java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: Ill
egal character in opaque part at index 11: jar:file:C:\DOCUME~1\David\LOCALS~1\T
emp\tempmm6286934818003944424/107.zip
java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: Ill
egal character in opaque part at index 11: jar:file:C:\DOCUME~1\David\LOCALS~1\T
emp\tempmm6286934818003944424/107.zip

有没有人知道如何以独立于平台的方式做到这一点?

1 个答案:

答案 0 :(得分:0)

我发现了问题。像这样的URI:

jar:file:C:/temp/yourmum.zip

无法在Windows上运行。它应该是:

jar:file:/C:/temp/yourmum.zip

所以我这样做了:

try {
        Path tempdir = Files.createTempDirectory("tempmm");
        tempdir.toFile().deleteOnExit();
        tempFilename = format("%s" + File.separator + "%s.zip", tempdir, meetId);

        if (tempFilename.contains(":\\")) {
            tempFilename = "/" + tempFilename;
        }

        // Handle windows
        tempFilename = tempFilename.replace("\\", "/");

        System.out.println("tempFilename = " + tempFilename);

        uri = URI.create("jar:file:" + tempFilename);

        System.out.println("temp file uri = " + uri.toString());

    } catch (IOException e) {
        log.severe(format("Unable to create temporary directory: %s", e.toString()));
    }

我不知道这是否是最佳解决方案,但它对我有用。 tild不是一个问题,它是分隔符。