40

I have to copy classpath resource from one package to another.

My program is:

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

        }

At Files.copy method I get exception:

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)

How to solve it?

Solution

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

This code correctly copies Movie.class from package com/stackoverflow/main into com/stackoverflow/json.

zb226
  • 8,586
  • 6
  • 44
  • 73
Jay Smith
  • 2,201
  • 3
  • 13
  • 26
  • 1
    This doesn't work because your classpath is composed of transparent and **opaque** resources - such as those inside a `jar`. You are trying to write to a path that looks something like `jar:file:/com/stackoverflow/json`, which is an invalid `Path` or `File` but a valid URI. In general, you cannot write to the classpath, only read from it. – Boris the Spider May 15 '17 at 06:47
  • No jar it is maven project – Jay Smith May 15 '17 at 06:49
  • When you compile a Maven project it will generate a jar. How else would you distribute your compiled code? (Pre Java 9 that is) – Boris the Spider May 15 '17 at 06:50
  • Does this answer your question? [Java NIO file path issue](https://stackoverflow.com/questions/9834776/java-nio-file-path-issue) – Pino Nov 14 '19 at 11:00

7 Answers7

52

problem is that Paths.get() doesnt expect that kind of value which is generated from uri.getPath().

Solution:

URI uri = ClassLoader.getSystemResource("com/stackoverflow/json").toURI();
String mainPath = Paths.get(uri).toString();
Path path = Paths.get(mainPath ,"Movie.class");
hunter
  • 3,478
  • 1
  • 14
  • 19
8

Try this:

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

to get the correct path. Worked for me after several hours trying to find out why I couldn't get the file from the jar. This works for NetBeans 8.02

lczapski
  • 3,838
  • 3
  • 13
  • 30
Fego
  • 85
  • 1
  • 5
5

I had the same issue and got the exception, noticed there was a space in the filename, so I had to trim it. After that, the issue is resolved.

Path filePath = Paths.get(dirPathStr, newFileName.trim());
svarog
  • 9,019
  • 4
  • 61
  • 71
techguy
  • 61
  • 1
  • 2
1

I have the same problem which I was facing from the past two days and finally, I got it Space causes such problem try to solve

var fileName=YourFileName.trim();
Path filePath = Paths.get(dirPathStr, fileName);
tryingToLearn
  • 9,007
  • 10
  • 70
  • 99
0

The following solutions work correctly:

Solution1:

String logFileLocalPath = "../log/log.txt";
File logFile = new File(getURL(logFileLocalPath).getPath());

Solution 2:

File logFile = new 
File(Paths.get(getURL(logFileLocalPath).toURI()).toString());

private static URL getURL(String localPath) {

      return Main.class.getResource(localPath);
}
Osadhi Virochana
  • 1,297
  • 2
  • 10
  • 19
Programmer
  • 47
  • 7
0

I faced same issue while using extentReports in my automation, i simply corrected the report path

public void config() {
    String path = System.getProperty("user.dir")+"\\reports\\index.html";       
    ExtentSparkReporter reporter = new ExtentSparkReporter(path);
    reporter.config().setReportName("Web Automation Reports");
    reporter.config().setDocumentTitle("Web Results");

... }

0

After trying many times, this worked for me

      Path path = new File(getClass().getResource("/data.json").getFile()).toPath(); 

Now you can use your path as you wish e.g

        Reader reader = Files.newBufferedReader(path);
Odwori
  • 762
  • 7
  • 13