How do I detect non-ASCII characters in string?

The code below detect if a given string has a non ASCII characters in it. We use the CharsetDecoder class from the java.nio package to decode string to be a valid US-ASCII charset.

package org.kodejava.io;

import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class NonAsciiValidation {
    public static void main(String[] args) {
        // This string contains a non ASCII character which will produce exception
        // in this program. While the second string has a valid ASCII only characters.
        byte[] invalidBytes = "Copyright © 2021 Kode Java Org".getBytes();
        byte[] validBytes = "Copyright (c) 2021 Kode Java Org".getBytes();

        // Returns a charset object for the named charset.
        CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();
        try {
            CharBuffer buffer = decoder.decode(ByteBuffer.wrap(validBytes));
            System.out.println(Arrays.toString(buffer.array()));

            buffer = decoder.decode(ByteBuffer.wrap(invalidBytes));
            System.out.println(Arrays.toString(buffer.array()));
        } catch (CharacterCodingException e) {
            System.err.println("The information contains a non ASCII character(s).");
            e.printStackTrace();
        }
    }
}

Below is the result of the program:

[C, o, p, y, r, i, g, h, t,  , (, c, ),  , 2, 0, 2, 1,  , K, o, d, e,  , J, a, v, a,  , O, r, g]
The information contains a non ASCII character(s).
java.nio.charset.MalformedInputException: Input length = 1
    at java.base/java.nio.charset.CoderResult.throwException(CoderResult.java:274)
    at java.base/java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:820)
    at org.kodejava.io.NonAsciiValidation.main(NonAsciiValidation.java:23)

How do I create temporary file?

A temporary file can be created by using java.io.File.createTempFile() method. It accepts the prefix, suffix and the path where the file will be stored. When no path is specified it will use the platform default temporary folder.

The name of the temporary file will be in the form of prefix plus five or more random characters plus the suffix. When the suffix is null a default .tmp will be used for suffix.

package org.kodejava.io;

import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;

public class TemporaryFileDemo {
    public static void main(String[] args) throws Exception {
        // Create a temporary file userlist.txt in the default platform
        // temporary folder / directory. We can get the platform temporary
        // folder using System.getProperty("java.io.tmpdir")
        File user = File.createTempFile("userlist", ".txt");

        // Delete the file when the virtual machine is terminated.
        user.deleteOnExit();

        // Create a temporary file data.txt in the user specified folder.
        File data = File.createTempFile("data", ".txt", new File("F:/Temp/Data"));
        data.deleteOnExit();

        // Write data into temporary file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(data))) {
            writer.write("750101,2008-01-01,BLUE,CAR");
            writer.write("750102,2008-09-06,RED,CAR");
            writer.write("750103,2008-05-01,GREEN,CAR");
            writer.write("750104,2008-06-08,YELLOW,CAR");
        }
    }
}

How do I display file contents in hexadecimal?

In this program we read the file contents byte by byte and then print the value in hexadecimal format. As an alternative to read a single byte we can read the file contents into array of bytes at once to process the file faster.

package org.kodejava.io;

import java.io.FileInputStream;

public class HexDumpDemo {
    public static void main(String[] args) throws Exception {
        // Open the file using FileInputStream
        String fileName = "F:/Wayan/Kodejava/kodejava-example/data.txt";
        try (FileInputStream fis = new FileInputStream(fileName)) {
            // A variable to hold a single byte of the file data
            int i = 0;

            // A counter to print a new line every 16 bytes read.
            int count = 0;

            // Read till the end of the file and print the byte in hexadecimal
            // valueS.
            while ((i = fis.read()) != -1) {
                System.out.printf("%02X ", i);
                count++;

                if (count == 16) {
                    System.out.println();
                    count = 0;
                }
            }
        }
    }
}

And here are some result from the file read by the above program.

31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 
37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 
33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 
39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 
35 36 37 38 39 30 0A 

How do I get the list of file system root?

The code below demonstrates how to obtain file system root available on your system. In Linux, you will have a single root (/) while on Windows you could get C:\ or D:\ that represent the root drives.

package org.kodejava.io;

import java.io.File;

public class FileSystemRoot {
    public static void main(String[] args) {
        // List the available filesystem roots.
        File[] root = File.listRoots();

        // Iterate the entire filesystem roots.
        for (File file : root) {
            System.out.println("Root: " + file.getAbsolutePath());
        }
    }
}

The result of the code snippet:

Root: C:\
Root: D:\
Root: F:\

How do I check if a directory is not empty?

package org.kodejava.io;

import java.io.File;

public class EmptyDirCheck {
    public static void main(String[] args) {
        File file = new File("D:/Downloads");

        // Check to see if the object represent a directory.
        if (file.isDirectory()) {
            // Get list of file in the directory. When its length is not zero
            // the folder is not empty.
            String[] files = file.list();

            if (files != null && files.length > 0) {
                System.out.println(file.getPath() + " is not empty!");
            }
        }
    }
}