Absolute Path of Project's folder in Java

前端 未结 3 1237
醉酒成梦
醉酒成梦 2020-12-09 23:34

Lots of confusion in this topic. Several Questions have been asked. Things still seem unclear. ClassLoader, Absolute File Paths etc etc

Suppose I have a project dire

3条回答
  •  长情又很酷
    2020-12-09 23:56

    First, make sure the lib directory is in your classpath. You can do this by adding the command line parameter in your startup script:

    $JAVA_HOME/bin/java -classpath .:lib com.example.MyMainClass
    

    save this as MyProject/start.sh or any os dependent script.

    Then you can access the textfile.txt (as rightly mentioned by Mark) as:

    // if you want this as a File
    URL res = getClass().getClassLoader().getResource("text/textfile.txt");
    File f = new File(res.getFile());
    
    // As InputStream
    InputStream in = getClass().getClassLoader()
            .getResourceAsStream("text/textfile.txt");
    

提交回复
热议问题