0

I need help getting a file from a file to use it. The file is specified in the -cp option when running jar through the console.

run the jar using:

java -cp myjar.jar:dir1/dir2/myfile.txt com.company.Main

execution result:

Exception in thread "main" java.lang.NullPointerException
  at com.company.Main.main(Main.java:11)

source code:

package com.company;

import java.io.InputStream;

public class Main {

    public static void main(String[] args) {
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream resource = classLoader.getResourceAsStream("dir1/dir2/myfile.txt");         
        System.out.println(resource.toString());
    }
}

project tree

-- сom
---- company
------ Main.java

How do I get that file from -cp?

2 Answers 2

2

Since you specify dir1/dir2/myfile.txt in the getResourceAsStream() call, you want the directory containing dir1 on the classpath, which would be the working directory, i.e. .:

java -cp myjar.jar:. com.company.Main

The classpath can only specify:

  • Directories
  • Jar files

No other type of file is supported.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply! I didn't really know about the classpath what you wrote me!
@Prot_CN The classpath is really implemented by URLClassLoader, and every entry in the classpath is a URL, defaulting to the file: protocol if not otherwise specified. As the javadoc says: "Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed." --- Which means that your .txt files was opened like a jar file, failed to read from it, and the classpath entry was then silently ignored from then on.
0

It appears that your computer cannot find the file. Right click on the file and select explorer to see the path or if you are using intellij idea you will see an option to copy the path when you right click on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.