Ich muss Classpath-Ressource von einem Paket in ein anderes kopieren.Ausnahme im Thread "Haupt" java.nio.file.InvalidPathException: Illegal char <:> bei Index 2:
Mein Programm ist:
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);
}
Bei Files.copy
Methode, die ich Ausnahme erhalten:
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)
Wie es zu lösen?
Lösung
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);
}
Dieser Code korrekt kopiert Movie.class
von Paket com/stackoverflow/main
in com/stackoverflow/json
.
Dies funktioniert nicht, da Ihr Klassenpfad aus transparenten und ** undurchsichtigen ** Ressourcen besteht, wie z. B. denen in einem "Jar". Sie versuchen, in einen Pfad zu schreiben, der ungefähr wie folgt aussieht: jar: file:/com/stackoverflow/json, was ein ungültiger Pfad oder eine Datei ist, aber ein gültiger URI. Im Allgemeinen können Sie nicht in den Klassenpfad schreiben, sondern nur davon lesen. –
Nein, es ist Maven-Projekt –
Wenn Sie ein Maven-Projekt kompilieren, wird es ein Glas erzeugen. Wie sonst würden Sie Ihren kompilierten Code verteilen? (Pre Java 9 ist das) –