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.example.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("C:/Data/Employee/data.tar.gz");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("/home/kodejava/kodejava.org/FileDemo.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 overwrite the unread data.

package org.kodejava.example.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 only clear the marker where you can write the data in the buffer and the unread data will be forgotten.

package org.kodejava.example.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 hold the value of how many data can be read from the buffer.

package org.kodejava.example.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 the a StringBuilder
        // object.
        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.example.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();
            }
        }
    }
}

How do I change the buffer mode between write and read?

A buffer can be read or written. To change the mode between the write mode and read mode we use the flip() method call on the buffer.

The are few things that you should know when you change between the write mode to the read mode. A buffer have the capacity, position and limit properties. The capacity will always be the same on write or read mode. But the position and limit will store different information in each mode.

In write mode the limit will be equals to the capacity, but in read mode the limit will be equals to the last position where the last data were written. The position on the write mode point where the data will be written in the buffer. When calling the flip() method the position will be set to 0 and the limit will be set to the last value of the position.

package org.kodejava.example.io;

import java.nio.CharBuffer;

public class BufferFlip {
    public static void main(String[] args) {
        CharBuffer buffer = CharBuffer.allocate(1024);
        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());

        buffer.put("Java NIO Programming");

        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());

        buffer.flip();
        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());
    }
}

The program will print the following result:

capacity = 1024
position = 0
limit    = 1024
capacity = 1024
position = 20
limit    = 1024
capacity = 1024
position = 0
limit    = 20

How do I write data into Buffer using put method?

The snippet below show you how to write some bytes into the java.nio.ByteBuffer object through a call to the put() method.

package org.kodejava.example.io;

import java.nio.ByteBuffer;

public class BufferPut {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put((byte) 65);
        buffer.put((byte) 66);
        buffer.put((byte) 67);
        buffer.put((byte) 68);
        buffer.put((byte) 69);


        // Writes a sequence of bytes
        byte[] bytes = new byte[] {70, 71, 72, 73, 74};
        buffer.put(bytes);

        // Write to the beginning of the buffer
        buffer.put(0, (byte) 75);

        buffer.flip();

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

How do I use a FileChannel to read data into a Buffer?

The example below show how to use a FileChannel to read some data into a Buffer. We create a FileChannel from a FileInputStream instance. Because a channel reads data into buffer we need to create a ByteBuffer and set its capacity. Read data from a channel into buffer using the FileChannel.read() method.

To read out the data from the buffer we need to flip the buffer first using the Buffer.flip() method. The method will change the buffer from writing-mode into reading-mode. After the entire buffer is read clear the buffer using the clear() method call.

package org.kodejava.example.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileRead {
    public static void main(String[] args) {
        String path = "D:/Temp/source.txt";
        try (FileInputStream fis = new FileInputStream(path); 
             FileChannel fileChannel = fis.getChannel()) {

            ByteBuffer buffer = ByteBuffer.allocate(64);

            int bytesRead = fileChannel.read(buffer);
            while (bytesRead != -1) {
                buffer.flip();

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

                buffer.clear();
                bytesRead = fileChannel.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I create a NIO Buffer?

This post show you how to use the java.nio buffer such as ByteBuffer, CharBuffer, DoubleBuffer, etc. To create a buffer you can use the allocate(int capacity) method. Each buffer object has the allocate(int capacity) method. When calling this method you need to pass the value of the capacity of the buffer to be created.

package org.kodejava.example.nio;

import java.nio.*;

public class BufferAllocate {
    public static void main(String[] args) {       
        ByteBuffer byteBuffer = ByteBuffer.allocate(64);
        CharBuffer charBuffer = CharBuffer.allocate(64);
        ShortBuffer shortBuffer = ShortBuffer.allocate(64);
        IntBuffer intBuffer = IntBuffer.allocate(64);
        LongBuffer longBuffer = LongBuffer.allocate(64);
        FloatBuffer floatBuffer = FloatBuffer.allocate(64);
        DoubleBuffer doubleBuffer = DoubleBuffer.allocate(64);
    }
}

How do I copy file using FileChannel class?

The example below show you how to copy a file using the java.nio.channels.FileChannel class.

package org.kodejava.example.io;

import java.io.*;
import java.nio.channels.FileChannel;

public class FileCopy {
    public static void main(String[] args) {
        //// Define the source and target file
        File source = new File("D:/Temp/source.txt");
        File target = new File("D:/Temp/target.txt");

        // Create the source and target channel
        try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
             FileChannel targetChannel = new FileOutputStream(target).getChannel()) {

            // Copy data from the source channel into the target channel
            targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}