Creating paths, Manipulating, Retrieving, Reading and Writing files


Creating paths

The Path class is used to programmaticaly represent a path in the file system (and can therefore point to files as well as directories, even to non-existent ones)

A path can be obtained using the helper class Paths:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.URI;
 
public class CustomPaths {
    public static void main(String[] args) {
        Path customPath1 = Paths.get("/usr/data");
        Path customPath2 = Paths.get(URI.create("file:///home/user/Documents/Report.txt"));
        Path customPath3 = Paths.get("D:\\Projects\\Files\\document.docx");
        Path customPath4 = Paths.get("/user/home", "john", "work", "notes.txt");
 
        // Perform operations with custom paths if needed
 
        System.out.println("Custom Path 1: " + customPath1);
        System.out.println("Custom Path 2: " + customPath2);
        System.out.println("Custom Path 3: " + customPath3);
        System.out.println("Custom Path 4: " + customPath4);
    }
}

Manipulating paths

Joining Two Paths

Paths can be joined using the resolve() method. The path passed has to be a partial path, which is a path that doesn't include the root element.

import java.nio.file.Path;
import java.nio.file.Paths;
 
public class CustomPathResolving {
    public static void main(String[] args) {
        Path customPath5 = Paths.get("/users/");
        Path customPath6 = Paths.get("john/documents");
        Path resolvedPath = customPath5.resolve(customPath6);
        Path otherResolvedPath = customPath5.resolve("david/files");
 
        // Perform operations with resolved paths if needed
 
        System.out.println("Resolved Path: " + resolvedPath);
        System.out.println("Other Resolved Path: " + otherResolvedPath);
 
        // Check equality using .equals() instead of ==
        System.out.println("Paths are equal: " + resolvedPath.equals(Paths.get("/users/john/documents")));
        System.out.println("Other Paths are equal: " + otherResolvedPath.equals(Paths.get("/users/david/files")));
    }
}

Normalizing a path

Paths may contain the elements . (which points to the directory you're currently in) and ..(which points to the parent directory).

When used in a path, . can be removed at any time without changing the path's destination, and .. can be removed together with the preceding element.

With the Paths API, this is done using the .normalize() method

import java.nio.file.Path;
import java.nio.file.Paths;
 
public class CustomPathNormalization {
    public static void main(String[] args) {
        Path customPath7 = Paths.get("/users/./john/../david/files");
        Path customPath8 = Paths.get("D:\\Data\\.\\..\\Temp");
        Path normalizedPath7 = customPath7.normalize();
        Path normalizedPath8 = customPath8.normalize();
 
        // Check equality using .equals() instead of ==
        System.out.println("Normalized Path 7: " + normalizedPath7);
        System.out.println("Normalized Path 8: " + normalizedPath8);
 
        System.out.println("Paths are equal: " + normalizedPath7.equals(Paths.get("/users/david/files")));
        System.out.println("Other Paths are equal: " + normalizedPath8.equals(Paths.get("D:\\Temp")));
    }
}

Retrieving information about a path

Information about a path can be get using the methods of a Path object:

1. toString() returns the string representation of the path
 
	Path p1 = Paths.get("/var/www"); // p1.toString() returns "/var/www"
 
2. getFileName() returns the file name (or, more specifically, the last element of the path
 
	Path p1 = Paths.get("/var/www"); // p1.getFileName() returns "www"
	Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt"); // p3.getFileName() returns "HHGTDG.odt"
 
3. getNameCount() returns the number of elements that form the path
 
	Path p1 = Paths.get("/var/www"); // p1.getNameCount() returns 2
 
4. getName(int index) returns the element at the given index
 
	Path p1 = Paths.get("/var/www"); // p1.getName(0) returns "var", p1.getName(1) returns "www"
 
5. getParent() returns the path of the parent directory
 
	Path p1 = Paths.get("/var/www"); // p1.getParent().toString() returns "/var"
 
6. getRoot() returns the root of the path
 
	Path p1 = Paths.get("/var/www"); // p1.getRoot().toString() returns "/"
	Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt"); // p3.getRoot().toString()
	returns "C:\\"

Retrieving information using the filesystem

To interact with the filesystem you use the methods of the class Files.

Checking existence

To check the existence of the file or directory a path points to, you use the following methods:

Files.exists(Path path)
 
and
 
Files.notExists(Path path)

!Files.exists(path) does not neccesarily have to be equal to Files.notExists(path), because there are three possible scenarios:

  • A file's or directory's existence is verified (exists returns true and notExists returns false in this case)
  • A file's or directory's nonexistence is verfied (exists returns false and notExists returns true)
  • Neither the existence nor the nonexistence of a file or a directory can be verified (for example due to access restrictions): Both exists and nonExists return false.

Checking whether a path points to a file or a directory

This is done using Files.isDirectory(Path path) and Files.isRegularFile(Path path)

Path p1 = Paths.get("/var/www");
Path p2 = Paths.get("/home/testuser/File.txt");
 
Files.isDirectory(p1) == true
Files.isRegularFile(p1) == false
 
Files.isDirectory(p2) == false
Files.isRegularFile(p2) == true

Getting properties

This can be done using the following methods:

Files.isReadable(Path path)
Files.isWritable(Path path)
Files.isExecutable(Path path)
 
Files.isHidden(Path path)
Files.isSymbolicLink(Path path)

Getting MIME type

Files.probeContentType(Path path)

This tries to get the MIME type of a file. It returns a MIME type String, like this:

  • text/plain for text files
  • text/html for HTML pages
  • application/pdf for PDF files
  • image/png for PNG files

Reading files

Files can be read byte- and line-wise using the Files class.

Path p2 = Paths.get(URI.create("file:///home/exampleuser/File.txt"));
byte[] content = Files.readAllBytes(p2);
List<String> linesOfContent = Files.readAllLines(p2);
 
Files.readAllLines() optionally takes a charset as parameter (default is StandardCharsets.UTF_8):
 
List<String> linesOfContent = Files.readAllLines(p2, StandardCharsets.ISO_8859_1);

Writing files

Files can be written bite- and line-wise using the Files class

Path p2 = Paths.get("/home/exampleuser/File.txt");
List<String> lines = Arrays.asList(new String[]{"First line", "Second line", "Third line"});
Files.write(p2, lines);
Files.write(Path path, byte[] bytes)

Existing files wile be overridden, non-existing files will be created.

Basic Programs