How do I get the extension of a file?

Below is an example that can be used to get the extension of a file. The code below assume that the extension is the last part of the file name after the last dot symbol. For instance if you have a file named data.txt the extension will be txt, but if you have a file named data.tar.gz the extension will be gz.

package org.kodejava.io;

import java.io.File;

public class FileExtension {
    private static final String EXT_SEPARATOR = ".";

    public static void main(String[] args) {
        File file = new File("data.txt");
        String ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/data.tar.gz");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/HelloWorld.java");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);
    }

    /**
     * Get the extension of the specified file.
     *
     * @param file a file.
     * @return the extension of the file.
     */
    private static String getFileExtension(File file) {
        if (file == null) {
            return null;
        }

        String name = file.getName();
        int extIndex = name.lastIndexOf(FileExtension.EXT_SEPARATOR);

        if (extIndex == -1) {
            return "";
        } else {
            return name.substring(extIndex + 1);
        }
    }
}

How do I clear a buffer using compact() method?

If you want to clear a buffer, but you want to keep the unread data in the buffer then you need to use the compact() method of the buffer. The compact() method will copy the unread data to the beginning of the buffer and set the position right after the unread data. The limit itself still have the value equals to the buffer capacity. The buffer will be ready to be written again without overwriting the unread data.

package org.kodejava.io;

import java.nio.CharBuffer;

public class BufferCompact {
    public static void main(String[] args) throws Exception {
        CharBuffer buffer = CharBuffer.allocate(64);
        buffer.put("Let's write some Java code! ");

        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // Read 10 chars from the buffer.
        buffer.flip();
        for (int i = 0; i < 10; i++) {
            System.out.print(buffer.get());
        }
        System.out.println();

        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // clear the buffer using compact() method.
        buffer.compact();
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // Write and read some more data.
        buffer.put("Add some more data.");

        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.print(buffer.get());
        }
    }
}

The output of the code snippet above is:

Position: 28
Limit   : 64
Let's writ
Position: 10
Limit   : 28
Position: 18
Limit   : 64
e some Java code! Add some more data.

How do I clear a buffer using clear() method?

The code below show you how to clear a buffer using the clear() method call. The clear method call set the position in the buffer to 0 and limit to the capacity of the buffer.

We usually call the clear() method after we read the entire content of a buffer and clear it for ready to be written again. The clear() method is actually not clearing the data in the buffer. It is only clear the marker where you can write the data in the buffer and the unread data will be forgotten.

package org.kodejava.io;

import java.nio.LongBuffer;

public class BufferClear {
    public static void main(String[] args) {
        // Allocates a new LongBuffer.
        LongBuffer buffer = LongBuffer.allocate(64);

        // Write the long array into the buffer.
        buffer.put(new long[]{10, 20, 30, 40, 50, 60, 70, 80});
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }

        // clear() method set the position to zero and limit
        // to the capacity of the buffer.
        buffer.clear();
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());
    }
}

The output of the code snippet:

Position: 8
Limit   : 64
10
20
30
40
50
60
70
80
Position: 0
Limit   : 64

How do I reread the content of a buffer?

The example shown below tells you how to reread the contents of a buffer. To reread the data from a buffer we can use the buffer’s rewind() method. This method set the position back to 0 while the limit is unchanged, it still holds the value of how many data can be read from the buffer.

package org.kodejava.io;

import java.nio.CharBuffer;

public class BufferRewind {
    public static void main(String[] args) {
        CharBuffer buffer = CharBuffer.allocate(1024);
        buffer.put("The quick brown fox jumps over the lazy dog.");
        buffer.flip();

        // Read buffer's data using the get() method call.
        while (buffer.hasRemaining()) {
            System.out.print(buffer.get());
        }
        System.out.println();

        // Rewind the buffer will set the position back to 0.
        // We rewind the buffer so that we can reread the buffer
        // data for another purposes.
        buffer.rewind();

        // Reread the buffer and append its data to a StringBuilder
        StringBuilder bufferText = new StringBuilder();
        while (buffer.hasRemaining()) {
            bufferText.append(buffer.get());
        }
        System.out.println(bufferText);
    }
}

The output of the code snippet:

The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.

How do I read data from a buffer into channel?

In this example you’ll see how to read data from buffer using FileChannel.write() method call. Reading from a buffer means that you are writing data into the channel object. In the snippet below the data from our dummy buffer will be read and written into the result.txt file.

package org.kodejava.io;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BufferRead {
    public static void main(String[] args) throws Exception {
        FileChannel channel = null;

        try {
            // Define an output file and create an instance of FileOutputStream
            File file = new File("result.txt");
            FileOutputStream fos = new FileOutputStream(file);

            // Create a dummy ByteBuffer which value to be read into a channel.
            ByteBuffer buffer = ByteBuffer.allocate(256);
            buffer.put(new byte[]{65, 66, 67, 68, 69, 70, 71, 72, 73, 74});

            // Change the buffer from writing mode to reading mode.
            buffer.flip();

            // Gets the channel from the FileOutputStream object and read the
            // data available in buffer using channel.write() method.
            channel = fos.getChannel();
            int bytesWritten = channel.write(buffer);
            System.out.println("written : " + bytesWritten);
        } finally {
            if (channel != null && channel.isOpen()) {
                channel.close();
            }
        }
    }
}