Dostępna w Javie klasa File daje kilka możliwości uzyskania ścieżki wyznaczonego pliku. Czym różnią się poszczególne metody? Oto porównanie – dla systemu Windows.
File file = new File("C:\\Users\\XYZ\\proj.png"); try { System.out.println("file.getAbsolutePath() = "+file.getAbsolutePath()); System.out.println("file.getCanonicalPath() = "+file.getCanonicalPath()); System.out.println("file.getName() = "+file.getName()); System.out.println("file.getParent() = "+file.getParent()); System.out.println("file.getPath() = "+file.getPath()); System.out.println("file.toString() = "+file.toString()); System.out.println("file.toPath().getFileName() = "+file.toPath().getFileName()); System.out.println("file.toPath().getFileSystem() = "+file.toPath().getFileSystem()); System.out.println("file.toPath().getName(0) = "+file.toPath().getName(0)); } catch (IOException e) { e.printStackTrace(); }
A oto wynik, jaki zwracają powyższe polecenia:
file.getAbsolutePath() = C:\Users\XYZ\proj.png
file.getCanonicalPath() = C:\Users\XYZ\proj.png
file.getName() = proj.png
file.getParent() = C:\Users\XYZ
file.getPath() = C:\Users\XYZ\proj.png
file.toString() = C:\Users\XYZ\proj.png
file.toPath().getFileName() = proj.png
file.toPath().getFileSystem() = sun.nio.fs.WindowsFileSystem@7471c619
file.toPath().getName(0) = Users