【发布时间】:2017-10-13 20:12:51
【问题描述】:
我必须将类路径资源从一个包复制到另一个包。
我的程序是:
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。
【问题讨论】:
-
这不起作用,因为您的类路径由透明和不透明资源组成——例如
jar中的资源。您正在尝试写入类似于jar:file:/com/stackoverflow/json的路径,这是一个无效的Path或File,但它是一个有效的URI。通常,您不能写入类路径,只能从中读取。 -
没有 jar 是 maven 项目
-
当你编译一个 Maven 项目时,它会生成一个 jar。你会如何分发你的编译代码? (即在 Java 9 之前)
-
这能回答你的问题吗? Java NIO file path issue