Java Reference
In-Depth Information
The first buffer that will hold the string length as type double will map to the beginning of the byte
buffer, buf . The view buffer into which we will place the string needs to map to the position in buf
immediately after the space required for the double value - 8 bytes from the beginning of buf in other
words. Remember that the first element in a view buffer maps to the current position in the byte buffer.
Thus, we can just set the position for buf to 8 before creating the view buffer, charBuf . All that's now
needed is the loop to load up the first two view buffers, create the third view buffer and load it, and then
write the file. Let's put the whole thing together as a working example.
Try It Out - Using Multiple View Buffers
The code for the loop is shaded in the following complete program:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class PrimesToFile2 {
public static void main(String[] args) {
int primesRequired = 100; // Default count
if (args.length > 0) {
try {
primesRequired = Integer.valueOf(args[0]).intValue();
} catch (NumberFormatException e) {
System.out.println("Prime count value invalid. Using default of "
+ primesRequired);
}
}
long[] primes = new long[primesRequired]; // Array to store primes
primes[0] = 2; // Seed the first prime
primes[1] = 3; // and the second
// Count of primes found - up to now, which is also the array index
int count = 2;
long number = 5; // Next integer to be tested
outer:
for (; count < primesRequired; number += 2) {
// The maximum divisor we need to try is square root of number
long limit = (long) Math.ceil(Math.sqrt((double) number));
// Divide by all the primes we have up to limit
for (int i = 1; i < count && primes[i] <= limit; i++)
if (number % primes[i] == 0) // Is it an exact divisor?
continue outer; // yes, try the next number
primes[count++] = number; // We got one!
}
File aFile = new File("C:/Beg Java Stuff/primes.txt");
FileOutputStream outputFile = null;
try {
Search WWH ::




Custom Search