Define file path in java

Java NIO Path (with Examples)

The Path class, introduced in the Java SE 7 release, is one of the primary entry points of the java.nio.file package. If our application uses Java New IO, we should learn more about the powerful features available in this class.

In this Java tutorial, we are learning 6 ways to create a Path .

Table of Contents 1. Building the absolute path 2. Building path relative to file store root 3. Building path relative to the current working directory 4. Building path from URI scheme 5. Building path using file system defaults 6. Building path using System.getProperty()

Prerequisite: I am building path for a file in location – “ C:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt “. I have created this file beforehand and will create Path to this file in all examples.

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.

Читайте также:  Магазин товаров для дома

To create an absolute path to a file, use getPath() method.

/** * Converts a path string, or a sequence of strings that when joined form a path string, * to a Path. If more does not specify any elements then the value of the first parameter * is the path string to convert. If more specifies one or more elements then each non-empty * string, including first, is considered to be a sequence of name elements and is * joined to form a path string. */ public static Path get(String first, String. more);

Example 1: Create an absolute Path to a file in Java NIO

In all given examples, we are creating the absolute path for the same file, in different ways.

//Starts with file store root or drive Path absolutePath1 = Paths.get("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt"); Path absolutePath2 = Paths.get("C:/Lokesh/Setup/workspace", "NIOExamples/src", "sample.txt"); Path absolutePath3 = Paths.get("C:/Lokesh", "Setup/workspace", "NIOExamples/src", "sample.txt");

2. Building path relative to file store root

Path relative to file store root starts with a forward-slash (“/”) character.

Example 2: Create relative Path to a given file

//How to define path relative to file store root (in windows it is c:/) Path relativePath1 = FileSystems .getDefault() .getPath("/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt"); Path relativePath2 = FileSystems .getDefault() .getPath("/Lokesh", "Setup/workspace/NIOExamples/src", "sample.txt");

3. Building path relative to current working directory

To define the path relative to the current working directory, do not use either file system root (c:/ in windows) or slash (“/”).

Example 3: Create relative Path to current working directory

In given example, the current working directory is NIOExamples .

//How to define path relative to current working directory Path relativePath1 = Paths.get("src", "sample.txt");

4. Building path from URI scheme

Not frequently, but at times we might face a situation where we would like to convert a file path in format “file:///src/someFile.txt” to NIO path.

Example 4: Get the absolute path of a file using file URI in Java NIO

//Writing c:/ is optional //URI uri = URI.create("file:///c:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt"); URI uri = URI.create("file:///Lokesh/Setup/workspace/NIOExamples/src/sample.txt"); String scheme = uri.getScheme(); if (scheme == null) throw new IllegalArgumentException("Missing scheme"); //Check for default provider to avoid loading of installed providers if (scheme.equalsIgnoreCase("file")) < String absPath = FileSystems.getDefault() .provider() .getPath(uri) .toAbsolutePath() .toString(); System.out.println(absPath); >//If you do not know scheme then use this code. //This code check file scheme as well if available. for (FileSystemProvider provider: FileSystemProvider.installedProviders()) < if (provider.getScheme().equalsIgnoreCase(scheme)) < String absPath = provider.getPath(uri) .toAbsolutePath() .toString(); System.out.println(absPath); >>

5. Building path using file system default

This is another variation of above examples where instead of using Paths.get() , we can use FileSystems.getDefault().getPath() method.

The rules for absolute and relatives paths are the same as the above methods.

Example 5: Get absolute path of a file using system defaults

FileSystem fs = FileSystems.getDefault(); //relative path Path path1 = fs.getPath("src/sample.txt"); //absolute path Path path2 = fs.getPath("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");

6. Building path using System.getProperty()

Well, this is off the course, but good to know. We can use system-specific System.getProperty() also to build Path for specific files.

Example 6: Get path of a file in the system download folder

Path path1 = FileSystems.getDefault() .getPath(System.getProperty("user.home"), "downloads", "somefile.txt");

Источник

File Path in Java

File Path in Java

  1. Reading a Java File
  2. How to Specify File Path in Java
  3. How to Get File Path in Java
  4. Conclusion

While working with files in Java, it is important to specify the correct file name and the correct path and extension.

The files we are working with might be present in the same or another directory. Depending on the location of the file, the pathname changes.

This article will discuss how to access and specify file paths in Java.

Reading a Java File

Reading a file means getting the content of a file. We use the Java Scanner class to read a file. Let us understand this through an example.

We will first write a Java program to create a new file. Then we will write another Java program to add some content to this newly created file.

Finally, we will read the contents of this file. Note that none of the programs in this article will run on an online compiler (use an offline compiler with the path correctly set).

Create a File

import java.io.File; import java.io.IOException;  public class Main   public static void main(String[] args)    //Try catch block  try    //Creating a file with the name demofile.txt  File myFile = new File("demofile.txt");   if (myFile.createNewFile())   System.out.println("The file is created with the name: " + myFile.getName());  > else   System.out.println("The file already exists.");  >  > catch (IOException x)   System.out.println("An error is encountered.");  x.printStackTrace();  >  > > 
The file is created with the name: demofile.txt 

This file gets created in the same directory where the Java files are present. All the Java program files are in the C directory.

Add Some Content to the File

import java.io.FileWriter; import java.io.IOException;  public class Main   public static void main(String[] args)   try   //create an object  FileWriter writeInFile = new FileWriter("demofile.txt");   //Adding content to this file  writeInFile.write("We are learning about paths in Java.");   writeInFile.close();  System.out.println("Successfully done!");  > catch (IOException x)   System.out.println("An error is encountered.");  x.printStackTrace();  >  > > 

Read the File

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; //scanner class for reading the file  public class Main   public static void main(String[] args)   try   File myFile = new File("demofile.txt");   //create the scanner object  Scanner readFile = new Scanner(myFile);   while (readFile.hasNextLine())   String data = readFile.nextLine();  System.out.println(data);  >  readFile.close();  > catch (FileNotFoundException x)   System.out.println("An error occurred.");  x.printStackTrace();  >  > > 
We are learning about paths in Java. 

Note that here, inside the File() method, we only pass the file’s name with its extension.

We are not specifying the complete path of the demofile.txt . The demofile.txt is present in the same directory and folder where we save all these Java program files.

However, if the demofile.txt is present in another directory or folder, reading this file is not that simple. In such cases, we specify the complete path of the file.

To get more details about the file system in Java, refer to this documentation.

How to Specify File Path in Java

To specify the path of a file, we pass the file’s name with its extension inside the File() method. We do it like this.

Note that the file name is sufficient only when the file is in the same folder as the working project’s directory. Otherwise, we have to specify the complete path of the file.

If you don’t know the file’s name, use the list() method. This method returns the list of all the files in the current directory.

Present in the File class of the java.io library, the list() method returns the list of all the files and directories as an array. The output it returns is based on the current directory defined by an abstract pathname.

If the abstract pathname does not denote a directory, the list() method returns null . Sometimes, we don’t know where the file is located.

Moreover, errors occur when the file we have to read is not present in the current working directory. Using the file’s complete path is better to avoid these issues.

To get the exact path of a file, use the methods given below.

How to Get File Path in Java

When we don’t know the path of a file, we can use some methods of Java to find the path of a file. Then, we can specify this pathname as an argument.

Java provides three types of file paths — absolute , canonical , and abstract . The java.io.file class has three methods to find the path of a file.

Get File Path Using getPath() Method in Java

The getPath() method belongs to the File class of Java. It returns the abstract file path as a string.

An abstract pathname is an object of java.io.file , which references a file on the disk.

import java.io.*; public class Main   public static void main(String args[])  try   //create an object  File myFile = new File("demo.txt");   //call the getPath() method  String path = myFile.getPath();  System.out.println("The path of this file is: " + path);  >  catch (Exception e)   System.err.println(e.getMessage());  >  > > 
The path of this file is: demo.txt 

As you can see in the output above, only the file’s name with the extension is the output. This shows that the file is present in the same folder where the Java program file is.

Get File Path Using getAbsolutePath() Method in Java

The getAbsolutePath() method returns a string as the file’s absolute path. If we create the file with an absolute pathname, then the getAbsolutePath() method returns the pathname.

However, if we create the object using a relative path, the getAbsolutePath() method resolves the pathname depending on the system. It is present in the File class of Java.

Note that the absolute path is the path that gives the complete URL of the file present in the system irrespective of the directory that it is in. On the other hand, the relative path gives the file’s path to the present directory.

//import the java.io library  import java.io.*;  public class Main   public static void main(String args[])    // try catch block  try   // create the file object  File myFile = new File("pathdemo.txt");   // call the getAbsolutePath() method  String absolutePath = myFile.getAbsolutePath();   System.out.println("The Absolute path of the file is: "+ absolutePath);  >  catch (Exception e)   System.err.println(e.getMessage());  >  > > 
The Absolute path of the file is: C:\Users\PC\pathdemo.txt 

Note that we get the complete working path this time, starting from the current working directory to the current folder in which the file is present.

So, whenever you don’t know the location of any file, use the absolute path method to find where the file is present. Then, you can specify that path whenever you have to read that file.

This way, the file to be read would be easily found.

Get the File Path Using getCanonicalPath() Method in Java

Present in the Path class returns the canonical path of a file. If the pathname is canonical, then the getCanonicalPath() method returns the file’s path.

The canonical path is always unique and absolute. Moreover, this method removes any . or .. from the path.

//import the java.io library  import java.io.*;  public class Main   public static void main(String args[])    // try catch block  try   // create the file object  File myFile = new File("C:\\Users");   // call the getCanonicalPath() method  String canonical = myFile.getCanonicalPath();   System.out.println("The Canonical path is : "+ canonical);  >  catch (Exception x)   System.err.println(x.getMessage());  >  > > 
The Canonical path is:C:\Users 

To read more about paths in Java, refer to this documentation.

Conclusion

In this article, we saw how we could specify the path of a file if we have to read it. We also studied the various methods like getPath() , getAbsolutePath() , and getCanonical() path that Java provides to get the path of a file.

Moreover, we saw how the path changes depending on the directory and folder of the file and current project. We also created and read some files as a demonstration.

These programs, however, will not run on online compilers.

Related Article — Java File

Related Article — Java Path

Источник

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