locating file in a classpath

前端 未结 1 911
一向
一向 2020-12-01 18:59

I\'m trying to read in file content, ex :

public void myMethod(){
     FileInputStream fstream = new FileInputStream(fileLocation);
     BufferedReader br =          


        
相关标签:
1条回答
  • 2020-12-01 19:25

    The Java IO API relies on the local disk file system, not on the classpath. Besides, using relative paths in Java IO stuff is recipe for portability trouble, don't rely on it. To allocate resources in the classpath you would normally use ClassLoader#getResource() or ClassLoader#getResourceAsStream().

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("src/main/resources/ids.txt");
    

    That said, you don't need that DataInputStream line. You're actually not taking any benefit from it.

    Update: if that doesn't work, then either the resource name is simply invalid or the file is actually not there in the classpath where you expect it to be. My cents on that the src folder is actually the root of the classpath and not part of a package. Remove it from the name.

    Update 2: to get all root disk file system paths which are covered by the runtime classpath do:

    for (URL root : Collections.list(Thread.currentThread().getContextClassLoader().getResources(""))) {
        System.out.println(root);
    }
    

    The resource name needs to be relative to either of them. That it is been placed in /WEB-INF/classes during the build is normal. It is covered by the classpath. Your problem lies somewhere else. Are you sure that the resource name is correct? Are you sure that you're running the code you think you are running?

    0 讨论(0)
提交回复
热议问题