Java File getPath()

Java File [Java File] Java File


getPath() Java java.io.File File

public String getPath()


getPath() File

  1. File
  2. File

import java.io.File;

public class GetPathExample {
    public static void main(String[] args) {
        // File
        File relativeFile = new File("docs/example.txt");
        System.out.println(": " + relativeFile.getPath());
       
        // File
        File absoluteFile = new File("/usr/local/docs/example.txt");
        System.out.println(": " + absoluteFile.getPath());
    }
}

: docs/example.txt
: /usr/local/docs/example.txt

getPath() vs getAbsolutePath()

  • getPath() File
  • getAbsolutePath()

File file = new File("docs/example.txt");
System.out.println("getPath(): " + file.getPath());
System.out.println("getAbsolutePath(): " + file.getAbsolutePath());

getPath(): docs/example.txt
getAbsolutePath(): /home/user/project/docs/example.txt

getPath() vs getCanonicalPath()

  • getPath()
  • getCanonicalPath()

1

getPath()

public void processFile(File inputFile) {
    try {
        // ...
        System.out.println(": " + inputFile.getPath());
    } catch (Exception e) {
        System.err.println(": " + inputFile.getPath());
    }
}

2

public boolean isConfigFile(File file) {
    return file.getPath().endsWith(".config");
}

  1. getPath()
  2. File / \
  3. File getPath()

// Windows
File file = new File("C:\\docs\\example.txt");
System.out.println(file.getPath()); // : C:\docs\example.txt

// UnixWindows
File file2 = new File("C:\\docs\\example.txt");
System.out.println(file2.getPath()); // : C:\docs\example.txt

File.getPath() File getAbsolutePath() getCanonicalPath()

Java File [Java File] Java File