How do I use LineNumberReader class to read file?

In this example we use LineNumberReader class to read file contents. What we try to do here is to get the line number of the read data. Instead of introducing another variable; an integer for instance; to keep track the line number we can utilize the LineNumberReader class. This class offers the getLineNumber() method to know the current line of the data that is read.

package org.kodejava.io;

import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.Objects;

public class LineNumberReaderExample {
    public static void main(String[] args) throws Exception {
        // We'll read a file called student.csv that contains our
        // student information data.
        String filename = Objects.requireNonNull(Thread.currentThread().getContextClassLoader()
                .getResource("student.csv")).getFile();

        // To create the FileReader we can pass in our student data
        // file to the reader. Next we pass the reader into our
        // LineNumberReader class.
        try (FileReader fileReader = new FileReader(filename);
             LineNumberReader lineNumberReader = new LineNumberReader(fileReader)) {
            // If we set the line number of the LineNumberReader here
            // we'll got the line number start from the defined line
            // number + 1

            //lineNumberReader.setLineNumber(400);

            String line;
            while ((line = lineNumberReader.readLine()) != null) {
                // We print out the student data and show what line
                // is currently read by our program.
                System.out.printf("Line Number %s: %s%n", lineNumberReader.getLineNumber(), line);
            }
        }
    }
}

The /resources/student.csv file:

Alice, 7
Bob, 8
Carol, 5
Doe, 6
Earl, 6
Malory, 8

And here is the result of our code snippet above:

Line Number 1: Alice, 7
Line Number 2: Bob, 8
Line Number 3: Carol, 5
Line Number 4: Doe, 6
Line Number 5: Earl, 6
Line Number 6: Malory, 8

How do I get total space and free space of my disk?

package org.kodejava.io;

import java.io.File;

public class FreeSpaceExample {
    public static void main(String[] args) {
        // We create an instance of a File to represent a partition
        // of our file system. For instance here we used a drive D:
        // as in Windows operating system. 
        File file = new File("D:");

        // Using the getTotalSpace() we can get an information of
        // the actual size of the partition, and we convert it to
        // mega bytes. 
        long totalSpace = file.getTotalSpace() / (1024 * 1024);

        // Next we get the free disk space as the name of the
        // method shown us, and also get the size in mega bytes.
        long freeSpace = file.getFreeSpace() / (1024 * 1024);

        // Just print out the values.
        System.out.println("Total Space = " + totalSpace + " Mega Bytes");
        System.out.println("Free Space = " + freeSpace + " Mega Bytes");
    }
}

Here is the result of the program:

Total Space = 1907605 Mega Bytes
Free Space = 946213 Mega Bytes

How do I rename a file or directory?

package org.kodejava.io;

import java.io.File;
import java.io.IOException;

public class FileRenameExample {
    public static void main(String[] args) throws IOException {
        // Creates a new file called OldHouses.csv
        File oldFile = new File("OldHouses.csv");
        boolean created = oldFile.createNewFile();
        System.out.println("File created? " + created);

        // Creates the target file.
        File newFile = new File("NewHouses.csv");

        // The renameTo() method renames file or directory to a
        // new name by passing the new destination file.
        boolean renamed = oldFile.renameTo(newFile);
        System.out.println("File renamed? " + renamed);
    }
}

How do I check if a file is hidden?

The File.isHidded() method checks to see if the file represented by aFile object is a hidden file. The definition of hidden is varied between operating systems. On UNIX based systems, a file is considered to be hidden when their name begins with a period character ('.'). On Windows operating system, a file is considered to be hidden if it has been marked hidden in the filesystem.

This File.isHidden() method returns true if and only if the file denoted by this File object is hidden according to the conventions of the underlying platform.

package org.kodejava.io;

import java.io.File;
import java.io.IOException;

public class FileHiddenExample {
    public static void main(String[] args) throws IOException {
        File file = new File("Hidden.txt");
        file.createNewFile();

        // We are using the isHidden() method to check whether a file
        // is hidden.
        if (file.isHidden()) {
            System.out.println("File is hidden!");
        } else {
            System.out.println("File is not hidden!");
        }
    }
}

If you want to set the file attribute to hidden in Windows operating system you can see it in the following example: How do I set the value of file attributes?

How do I get the content of a directory?

In this example you’ll see how to read the list of files inside a directory. To get this functionality we can use the File.listFiles() method. This method return an array of File object which can be either an instance of file or directory.

package org.kodejava.io;

import java.io.File;
import java.io.FilenameFilter;

public class DirectoryContentExample {
    public static void main(String[] args) {
        File gamesDir = new File("D:/Games");

        // Get a list of file under the specified directory above 
        // and return it as an abstract file object.
        File[] files = gamesDir.listFiles();

        if (files != null) {
            // Iterates the content of gamesDir directory, print 
            // it and check it whether it was a directory or a 
            // file.
            for (File file : files) {
                System.out.println(file + " is a "
                    + (file.isDirectory() ? "directory" : "file"));
            }
        }

        // Here we also get the list of file in the directory but
        // return it just as an array of String.
        String[] strings = gamesDir.list();
        if (strings != null) {
            for (String file : strings) {
                System.out.println("File = " + file);
            }
        }

        // Now we want to list the file in the directory but we 
        // just want a file with a .doc extension. To do this we 
        // first create a FilenameFilter which will be given to 
        // the listFiles() method to filter the listing process. 
        // The rule of filtering is implemented in the accept() 
        // method of the FilenameFilter interface, and we can write
        // it using lambda expression as follow.
        FilenameFilter filter = (dir, name) -> name.endsWith(".docx");

        // Give me just a .doc files in your directory.
        File[] docs = gamesDir.listFiles(filter);
        if (docs != null) {
            for (File doc : docs) {
                System.out.println("Doc file = " + doc);
            }
        }
    }
}

Here is the result of the program:

The File[] array returned:

D:\Games\AOE is a directory
D:\Games\Championship Manager 2017 is a directory
D:\Games\GameHouse is a directory
D:\Games\Sierra is a directory
D:\Games\testing.doc.docx is a file
D:\Games\TTD is a directory

The String[] array returned:

File = AOE
File = Championship Manager 2017
File = GameHouse
File = Sierra
File = testing.docx
File = TTD

The File[] array using FilenameFilter result:

Doc file = D:\Games\testing.docx