MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

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

public class MainClass {
    public static void main(String[] args) {
        File aFile = new File("primes.txt");
        FileInputStream inFile = null;
        try {
            inFile = new FileInputStream(aFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.err);
        }
        FileChannel inChannel = inFile.getChannel();
        try {
            ByteBuffer lengthBuf = ByteBuffer.allocate(8);
            while (true) {
                if (inChannel.read(lengthBuf) == -1) {
                    break;
                }
                lengthBuf.flip();
                int strLength = (int) lengthBuf.getDouble();
                ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);
                if (inChannel.read(buf) == -1) {
                    break;
                }
                buf.flip();
                byte[] strChars = new byte[2 * strLength];
                buf.get(strChars);
                System.out.println(strLength);
                System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
                System.out.println(buf.getLong());
                lengthBuf.clear();
            }
            inFile.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
}