gpt4 book ai didi

java.nio.file.InvalidPathException : Illegal char <:> at index 2:

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:57 25 4
gpt4 key购买 nike

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

我的程序是:

    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/main 复制到 com/stackoverflow/json

最佳答案

问题是 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");

关于java.nio.file.InvalidPathException : Illegal char <:> at index 2:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43972777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com