是否有一个API来获取类路径资源(例如我得到的Class.getResource(String))作为一个java.nio.file.Path?理想情况下,我想使用奇特的新Path API和类路径资源.
我必须将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(); …Run Code Online (Sandbox Code Playgroud)