Absolute path to Project folder in Java

A lot of confusion on this topic. Several Questions were asked. Things still seem obscure. ClassLoader, Absolute file paths, etc. Etc.

Suppose I have a project directory structure, since

MyProject--
            --dist        
            --lib
            --src
            --test

I have a resource that says "txtfile.txt" in the "lib / txt" directory. I want to access it regardless of the system. I need an absolute project path. Therefore, I can encode the path as abspath + "/lib/Dictionary/txtfile.txt"

Suppose i do it

 java.io.File file = new java.io.File("");   //Dummy file
    String  abspath=file.getAbsolutePath();

I get the current working directory, which is not necessarily the root of the project.

, "prj.jar" "dist", "lib/txt/txtfile.txt", . dist.

, .

+3
3

getResource() getResourceAsStream() . , ClassLoader .

- getClass().getResource("lib/txtfile.txt"), .

: , , , - - (, JAR). - , URL- , ClassLoader URL-. , , URL- getResourceAsStream.

, ClassLoader, ( JAR ). ! ClassLoader Class-Path , , Class-Path, . ., ClassLoader - JAR , , , , .

., ClassLoader JAR, ClassLoader JAR .

, JAR lib foo.txt, , getResource("lib/foo.txt");

JAR, getResource("./lib/foo.txt");

+9

, lib . , script:

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

MyProject/start.sh os script.

textfile.txt( Mark) :

// 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");
+2

@Mark . , , .

, File, :

  • System "java.class.path" ,
  • JAR ,
  • , "../.." JAR pathname, "project"
  • .

- script -D. , script ; whence.

0

Source: https://habr.com/ru/post/1753824/


All Articles