Java Reference
In-Depth Information
ByteBuffer buf = ByteBuffer.allocateDirect(2*maxLength + 4);
System.out.println("Buffer is "+ (buf.isDirect()?"":"not")+"direct.");
This outputs a line telling you whether the program is working with a direct buffer or not. If it is, it will
produce the following output:
Buffer is direct.
Proverbs written to file.
Writing Numerical Data Using a Channel
Let's see how you could set up the primes-generating program from Chapter 4 to write the primes to a file
instead of outputting them to the command line. You base the new code on the MorePrimes version of the
program. Ideally, you could add a command-line argument to specify how many primes you want. This is
not too difficult. Here's how the code starts off:
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;
import static java.lang.Math.min;
public class PrimesToFile {
public static void main(String[] args) {
int primesRequired = 100; // Default prime 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);
}
// Method to generate the primes...
// Method to create the file path...
// Method to write the file...
}
}
}
Here, if you don't find a command-line argument that you can convert to an integer, you just use a default
count of 100. The static import statements enable you to use the static methods in the Math class that you
need for the calculation without qualifying their names.
You can now generate the primes with code similar to that in Chapter 4 as follows:
// Calculate enough primes to fill the array
private static long[] getPrimes(long[] primes) {
primes[0] = 2L; // Seed the first prime
primes[1] = 3L; // and the second
// Count of primes found - up to now, which is also the array index
int count = 2;
// Next integer to be tested
long number = 5L;
Search WWH ::




Custom Search