Java programming language

File management

Filesystem management

  

In this document we are going to talk about the classes provided by Java to manage our file system. We will learn how to do some basic operations, such as:

1. File class

File class is the most basic (and ancient) class to deal with our filesystem. It also belongs to java.io package, and has some methods to:

For instance, this piece of code checks if a file exists in our system:

if (! (new File("example.txt")).exists() ) 
{
    System.err.println("File example.txt not found");
}
else
{
    // File exists
}

This other piece of code lists all the files and folders of a given folder in the system. For every subfolder, it marks it as DIR, and for every file, it prints its size in KB.

File location = new File("D:" + File.separatorChar + "Downloads");
File[] contents = location.listFiles();
for(File f: contents)
{
    System.out.print(f.getName());
    if (f.isDirectory())
        System.out.println (" (DIR)");
    else
        System.out.println (" " + (f.length() / 1024) + "KB");
}

Note that we can use File.separatorChar property from File class to represent the separator char of current operating system. This will be \ in Windows, or / in Linux (although you can also use / in Windows systems).

2. Path and Paths

Path is an interface representing a path in the system (this is, a sequence of folders and subfolders pointing to a given location). It is a newer element in Java API, that belongs to java.nio package, and it provides some useful methods, such as:

Paths class contains some static methods to deal with paths. It also belongs to java.nio package, and lets us, for instance, get a Path object from a given route:

Path location = Paths.get("/home/user/myFolder");
System.out.println("Parent folder is " + location.getParent().toString());

3. Files class

Files class is also a newer class in the Java API (it belongs to java.nio package) with a list of static methods to deal with our filesystem:

This piece of code reads the whole contents of a text file in one single line, and then we can just explore the List returned:

try
{
    List<String> data = Files.readAllLines(Paths.get("data/file.txt"));
    for(String line: data)
    {
        ...
    }
}
catch (IOException ex)
{
    ...
}