Java NIO : write small size file using FileChannel

Write the file Using ByteBuffer and FileChannel from String:

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class WriteFileUsingFileChannel {

    public static void main(String args[]) throws IOException {
        String content = "Text content";
        Path file = Paths.get(URI.create("file:///D:/TestFile.txt"));
        FileChannel fileChannel = FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

        ByteBuffer buffer = ByteBuffer.allocate(content.length());
        buffer.put(content.getBytes());
        buffer.flip();

        fileChannel.write(buffer);

        fileChannel.close();
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s