Getting absolute path java

Getting Filesystem Paths in Java

Learn the difference between path, absolute and canonical paths. Also, learn to get the path of a file in Java using standard IO and New IO classes.

1. Relative, Absolute and Canonical Paths

A relative path is a path that describes the location of a file or folder in relative to the current working directory. Unlike absolute paths, relative paths contain information that is only relative to the current directory.

This is the path, which we generally provide in the File class’s constructor.

src\main\java\com\howtodoinjava\io\foo\foo.txt src\main\java\com\howtodoinjava\io\foo\bar\bar.txt

An absolute path always contains the root element and the complete directory hierarchy required to locate the file. There is no more information required further to access the file or path.

  • Absolute paths contain all the relevant information to find the resources indicated by an absolute URL.
  • Absolute paths may contain the shorthands like single and double dots in the file paths.
C:\Users\lokesh\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\foo.txt C:\Users\lokesh\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\bar\..\foo.txt

Canonical paths are absolute paths after resolving the shorthands or redundant names like dots “ . ” and “ .. ” as per the directory structure.

The canonical path of a file just “purifies” the path to the absolute path, removing and resolving stuff like dots and resolving symlinks (on UNIX).

C:\Users\lokesh\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\foo.txt C:\Users\lokesh\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\bar\bar.txt

2. Get File Paths Using java.io.File

The java.io.File class has three methods to obtain the filesystem paths:

  • file.getPath() : returns the same string passed as the File constructor.
  • file.getAbsolutePath() : returns the pathname of the file after resolving the path for the current user’s directory. It does not resolve the shorthands like single and double dots.
  • file.getCanonicalPath() : returns the full path after resolving the absolute pathname as well as the shorthands.
File file = new File("src/main/java/com/howtodoinjava/io/foo/bar/../foo.txt"); String givenPath = file.getPath(); String absPath = file.getAbsolutePath(); String canPath = file.getCanonicalPath(); System.out.println(givenPath); System.out.println(absPath); System.out.println(canPath);
src\main\java\com\howtodoinjava\io\foo\bar\..\foo.txt C:\Users\lokes\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\bar\..\foo.txt C:\Users\lokes\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\foo.txt

3. Get File Paths Using java.nio.file.Path

The java.nio.file.Path also provides following methods for getting various paths:

  • path.toAbsolutePath() – Full file path similar to file.getAbsolutePath().
  • path.toRealPath() – Canonical path similar to file.getCanonicalPath().

The Path methods throws NoSuchFileException if the file is not present in the specified location. The File methods do not throw any exceptions.

Path path = Path.of("src/main/java/com/howtodoinjava/io/foo/bar/../foo.txt"); givenPath = path.toString(); absPath = path.toAbsolutePath().toString(); canPath = path.toRealPath().toString(); System.out.println(givenPath); System.out.println(absPath); System.out.println(canPath);
src\main\java\com\howtodoinjava\io\foo\bar\..\foo.txt C:\Users\lokes\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\bar\..\foo.txt C:\Users\lokes\IdeaProjects\Core-Java\src\main\java\com\howtodoinjava\io\foo\foo.txt

In this tutorial, we understood different kinds of filesystem paths in Java and how to get these paths using Java APIs.

Читайте также:  Php get class instance

As a best practice, always use the canonical paths if we are not sure if the provided path contains the shorthand characters or not.

Источник

Java File Path, Absolute Path and Canonical Path

Java File Path, Absolute Path and Canonical Path

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java File Path

  1. getPath() : This file path method returns the abstract pathname as String. If String pathname is used to create File object, it simply returns the pathname argument. If URI is used as argument then it removes the protocol and returns the file name.
  2. getAbsolutePath() : This file path method returns the absolute path of the file. If File is created with absolute pathname, it simply returns the pathname. If the file object is created using a relative path, the absolute pathname is resolved in a system-dependent way. On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
  3. [getCanonicalPath](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalPath())() : This path method returns the canonical pathname that is both absolute and unique. This method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as “.” and “…” from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).

Java File Path Example

Let’s see different cases of the file path in java with a simple program.

package com.journaldev.files; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; public class JavaFilePath < public static void main(String[] args) throws IOException, URISyntaxException < File file = new File("/Users/pankaj/test.txt"); printPaths(file); // relative path file = new File("test.xsd"); printPaths(file); // complex relative paths file = new File("/Users/pankaj/../pankaj/test.txt"); printPaths(file); // URI paths file = new File(new URI("file:///Users/pankaj/test.txt")); printPaths(file); >private static void printPaths(File file) throws IOException < System.out.println("Absolute Path: " + file.getAbsolutePath()); System.out.println("Canonical Path: " + file.getCanonicalPath()); System.out.println("Path: " + file.getPath()); >> 

java file path, file path in java, absolute path, canonical path

Below image shows the output produced by the above java file path program. The output is self-explanatory. Based on the output, using the canonical path is best suitable to avoid any issues because of relative paths. Also, note that the java file path methods don’t check if the file exists or not. They just work on the pathname of the file used while creating the File object. That’s all for different types of the file path in java.

Читайте также:  In order traversal java

You can checkout more java IO examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Still looking for an answer?

Hi Sir, I am trying to get the full path of the selected file. Below is the code. Please advise. I need to pass the full path and file name for the selected files to apache pdf box class to get the excel extracts. /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pdfet.pdfext; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.event.ActionListener; //import com.pdfet.pdfext.ExtensionFileFilter; import java.io.File; import javax.swing.filechooser.FileFilter; /** * * @author vak_salem */ class ExtensionFileFilter extends FileFilter < String descrip; String extn[]; public ExtensionFileFilter(String descrip,String Extn) < this(descrip,new String[] ); > public ExtensionFileFilter(String descrip, String extn[]) < if (descrip==null) < this.descrip=extn[0] + “”; > else < this.descrip=descrip; >this.extn=(String []) extn.clone(); toLower(this.extn); > private void toLower(String array[]) < for (int i=0,n=array.length;i// return (array.toString()); > public String getDescription() < return descrip; >public boolean accept(File file) < if (file.isDirectory()) < return true; >else < String path = file.getAbsolutePath().toLowerCase(); for (int i = 0, n = extn.length; i < n; i++) < String ex = extn[i]; if ((path.endsWith(ex) && (path.charAt(path.length() - ex.length() - 1)) == ‘.’)) < return true; >> > return false; > > public class Jcustomfhooser< public static void main(String args[]) < JFrame frame=new JFrame(“PDF2Excel”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(700, 700); //JPanel panel=new JPanel(); JLabel label=new JLabel(“Upload file and click Submit”); Container pane= frame.getContentPane(); JFileChooser jfc =new JFileChooser(“UploadFile”); jfc.setMultiSelectionEnabled(true); // FileFilter pdffilter=new ExtensionFileFilter(null,new String[] ); //ExtUI ex=new ExtUI(); //String outstr; //ExtensionFileFilter ex=new ExtensionFileFilter(); FileFilter filter= new ExtensionFileFilter(null,new String[] ); // FileFilter pdffilter=new ExtensionFileFilter //jfc.setFileSelectionMode(JFileChooser.; jfc.setFileFilter(filter); //jfc.addChoosableFileFilter(filter); JButton button=new JButton(“Select Files…”); button.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < int retval=jfc.showOpenDialog(frame); if (retval==JFileChooser.APPROVE_OPTION) < //File file=new File(); >File[] selectedfiles =jfc.getSelectedFiles(); StringBuilder sb=new StringBuilder(); for (int i=0;i JOptionPane.showMessageDialog(frame, sb.toString()); > > >); //jfc.showOpenDialog(null); pane.setLayout(new GridLayout(3,1,10,10)); pane.add(label); //panel.add(jfc); pane.add(button); //frame.getContentPane().add(BorderLayout.NORTH,panel); //frame.getContentPane().add(BorderLayout.WEST,) frame.setSize(200, 200); frame.setVisible(true); > > — Arun

Читайте также:  Python словари значение по умолчанию

Источник

Get absolute file path in Java example

Get absolute file path example shows how to get the absolute path of a file in Java. The example also shows the difference between path, absolute path, and canonical path.

How to get the absolute file path in Java?

We can use the getAbsolutePath method of Java File class to get the absolute file path.

This method returns the absolute path of the file as a string.

Example

As you can see from the output, I created the file without specifying the complete path but I when printed the absolute path, it gave the complete path of the file in the file system.

What is the difference between path, absolute path, and canonical path?

Java File class provides three methods namely getPath , getAbsolutePath and getCanonicalPath . All three methods return a string containing the path information of the file, but they differ from one another.

getPath(): This method returns a path that was used to create a File object. In short, it is the path using which the File object was first created.

getAbsolutePath(): This method returns a path that is a fully qualified path (after resolving the path relative to the current directory, if the relative path was used while creating the File object).

getCanonicaPath(): This method returns the path which is similar to the absolute path but it also converts . (Current directory) and .. (Parent directory) to the actual directories. It also resolves any symbolic links before returning the canonical path.

There can be only one canonical path but there could be many absolute paths for the same file. Sounds confusing? Let’s see an example.

Источник

Оцените статью