Reading a file from a jar, or anywhere on the classpath?

后端 未结 2 416
情书的邮戳
情书的邮戳 2021-02-06 12:24

I\'m trying to build an application that builds a resource file into a jar, but I\'d like to have the project runnable within eclipse. I have a basic maven 2 structure for my pr

2条回答
  •  攒了一身酷
    2021-02-06 13:04

    I don't understand your problem. Resources from src/main/resources are automatically copied over to target/classes and are thus available on the classpath under Maven and Eclipse relatively to the root level at the same location (unless your Eclipse project is not properly configured).

    And when packaged inside a JAR, the content of target/classes is packaged "as is" so nothing is changed.

    In other words, accessing your file.txt like this is perfectly fine (and this is actually how things are documented):

    // Retrieve resource
    InputStream is = getClass().getResourceAsStream( "/file.txt" );
    
    // Do something with the resource
    
    ...
    

    If you have a problem somewhere, please clarify.

    Update: I did a quick test with the maven-eclipse-plugin and I can't reproduce your problem:

    $ mvn archetype:generate -DgroupId=com.stackoverflow -DartifactId=q2467362 -Dversion=1.0-SNAPSHOT
    ...
    $ cd q2467362
    $ mkdir -p src/main/resources
    $ mvn eclipse:eclipse
    ...
    $ cat .classpath
    
      
      
      
      
      
      
    
    

    The directory src/main/resources is added as source folder as expected. Can you show your POM (especially the resources element if you define one)?

提交回复
热议问题