java.nio.file.InvalidPathException:索引 2 处的非法字符 <:>:

新手上路,请多包涵

我必须将类路径资源从一个包复制到另一个包。

我的程序是:

     public static void main(String[] args) throws IOException, URISyntaxException {

            ClassLoader classLoader = CopyFileToDirectoryTest.class.getClassLoader();
InputStream in = classLoader.getResourceAsStream("com/stackoverflow/main/Movie.class");

            URI uri = ClassLoader.getSystemResource("com/stackoverflow/json").toURI();
            Path path = Paths.get(uri.getPath(),"Movie.class");
            System.out.println(path);

            long copy = Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
            System.out.println(copy);

        }

Files.copy 方法我得到异常:

 Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 2: /D:/Programs/workspaceEE/HibernateDemo/target/classes/com/stackoverflow/json
    at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    at java.nio.file.Paths.get(Paths.java:84)
    at com.stackoverflow.main.CopyFileToDirectoryTest.main(CopyFileToDirectoryTest.java:34)

如何解决?

解决方案

public static void main(String[] args) throws IOException, URISyntaxException {
        ClassLoader classLoader = CopyFileToDirectoryTest.class.getClassLoader();
        InputStream in = classLoader.getResourceAsStream("com//stackoverflow//main//Movie.class");
        URI uri = ClassLoader.getSystemResource("com//stackoverflow//json").toURI();
        String mainPath = Paths.get(uri).toString();
        Path path = Paths.get(mainPath, "Movie.class");
        System.out.println(path);
        long copy = Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
        System.out.println(copy);
    }

此代码正确地 Movie.class 从包 com/stackoverflow/maincom/stackoverflow/json

原文由 Jay Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

问题是 Paths.get() 不期望从 uri.getPath() 生成的那种值。

解决方案:

 URI uri = ClassLoader.getSystemResource("com/stackoverflow/json").toURI();
String mainPath = Paths.get(uri).toString();
Path path = Paths.get(mainPath ,"Movie.class");

原文由 hunter 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试这个:

 Path path = new File(getClass()
.getResource("/<path to the image in your build/classes folder>")
.getFile()).toPath();

得到正确的路径。几个小时后为我工作,试图找出为什么我无法从 jar 中获取文件。这适用于 NetBeans 8.02

原文由 Fego 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题