Reference files in java

Class File

The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator , and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.

A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked.

The parent of an abstract pathname may be obtained by invoking the getParent() method of this class and consists of the pathname’s prefix and each name in the pathname’s name sequence except for the last. Each directory’s absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory’s absolute pathname. For example, the directory denoted by the abstract pathname «/usr» is an ancestor of the directory denoted by the pathname «/usr/local/bin» .

  • For UNIX platforms, the prefix of an absolute pathname is always «/» . Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix «/» and an empty name sequence.
  • For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by «:» and possibly followed by «\\» if the pathname is absolute. The prefix of a UNC pathname is «\\\\» ; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.

Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.

Читайте также:  Set all values in java map

A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object’s owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.

Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

Interoperability with java.nio.file package

The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path represented by a File object to locate a file. The resulting Path may be used with the Files class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.

Источник

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

Источник

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