Java Reference
In-Depth Information
outer:
for (; count < primes.length ; number += 2) {
// The maximum divisor we need to try is square root of number
long limit = (long)ceil(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] == 0L)
// Is it an exact divisor?
continue outer;
// yes, try the next number
primes[count++] = number;
// We got one!
}
return primes;
}
PrimesToFile.java
Here's how the method to create the file path looks:
// Create the path for the named file in the specified directory
// in the user home directory
private static Path createFilePath(String directory, String fileName) {
Path file = Paths.get(System.getProperty("user.home")).
resolve(directory).resolve(fileName);
try {
// Make sure we have the directory
Files.createDirectories(file.getParent());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("New file is: " + file);
return file;
}
PrimesToFile.java
Now all you need to do is add the code to write the primes to the file. Let's put this into a working ex-
ample.
TRY IT OUT: Writing Primes to a File
This program splits the primes calculation, the creation of the file path, and the operations to write the
file, into separate methods. Here's the complete example, with the method that writes the file shown
shaded:
Search WWH ::




Custom Search