import static java.lang.Math.min;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
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.bin");
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);
LongBuffer longBuf = buf.asLongBuffer();
int primesWritten = 0;
while (primesWritten < primes.length) {
longBuf.put(primes, primesWritten, min(longBuf.capacity(), primes.length - primesWritten));
buf.limit(8 * longBuf.position());
try {
file.write(buf);
primesWritten += longBuf.position();
} catch (IOException e) {
e.printStackTrace(System.err);
}
longBuf.clear();
buf.clear();
}
try {
System.out.println("File written is " + file.size() + "bytes.");
outputFile.close();
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}