MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.LongBuffer;
import java.nio.channels.FileChannel;

public class MainClass {
    public static void main(String[] args) {
        long[] primes = new long[] { 1, 2, 3, 5, 7 };
        File aFile = new File("C:/test/primes.txt");
        FileOutputStream outputFile = null;
        try {
            outputFile = new FileOutputStream(aFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.err);
        }
        FileChannel file = outputFile.getChannel();
        final int BUFFERSIZE = 100;
        ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
        DoubleBuffer doubleBuf = buf.asDoubleBuffer();
        buf.position(8);
        CharBuffer charBuf = buf.asCharBuffer();
        for (long prime : primes) {
            String primeStr = "prime = " + prime;
            doubleBuf.put(0, (double) primeStr.length());
            charBuf.put(primeStr);
            buf.position(2 * charBuf.position() + 8);
            LongBuffer longBuf = buf.asLongBuffer();
            longBuf.put(prime);
            buf.position(buf.position() + 8);
            buf.flip();
            try {
                file.write(buf);
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
            buf.clear();
            doubleBuf.clear();
            charBuf.clear();
        }
        try {
            System.out.println("File written is " + file.size() + "bytes.");
            outputFile.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
}