线程"main"中的异常java.nio.file.InvalidPathException:索引2处的非法char <:>:

Jay*_*ith 14 java nio

我必须将classpath资源从一个包复制到另一个包.

我的计划是:

    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);

        }
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

怎么解决?

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);
    }
Run Code Online (Sandbox Code Playgroud)

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

hun*_*ter 21

问题是,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");
Run Code Online (Sandbox Code Playgroud)


小智 6

尝试这个:

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

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


小智 5

我遇到了同样的问题并得到了异常,注意到文件名中有一个空格,所以我不得不修剪它。之后,问题就解决了。

Path filePath = Paths.get(dirPathStr, newFileName.trim());
Run Code Online (Sandbox Code Playgroud)