Java Reference
In-Depth Information
fibonumbers
ByteBuffer buf = ByteBuffer.allocate(count*8); // Buffer for
output
LongBuffer longBuf = buf.asLongBuffer();
// View buffer for
type long
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("fibonnaci.bin");
try {
// Create parent directory if it doesn't exist
Files.createDirectories(file.getParent());
} catch(IOException e) {
System.err.println("Error creating directory: " +
file.getParent());
e.printStackTrace();
System.exit(1);
}
System.out.println("New file is: " + file);
try(BufferedOutputStream fileOut =
new
BufferedOutputStream(Files.newOutputStream(file))){
// Generate Fibonacci numbers in buffer
for(int i = 0 ; i < count ; ++i) {
if(i < 2)
fiboNumbers[index] = i;
else
fiboNumbers[index] = fiboNumbers[0] + fiboNumbers[1];
longBuf.put(fiboNumbers[index]);
index = ++index%2;
}
// Write the numbers to the file
fileOut.write(buf.array(), 0, buf.capacity());
System.out.println("File written.");
} catch(IOException e) {
System.err.println("Error writing file: " + file);
e.printStackTrace();
}
}
}
StreamOutputToFile.java
This example generates 50 Fibonacci numbers and writes them to the fibonacci.bin file. The only out-
put if everything works as it should is the file path and a message confirming the file has been written.
Search WWH ::




Custom Search