简体   繁体   中英

How do I use the file from classpath?

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?

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 , ie . :

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

The classpath can only specify:

  • Directories
  • Jar files

No other type of file is supported.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM