Java Reference
In-Depth Information
METHOD DESCRIPTION
flush() Flushes the stream causing all data in the internal buffer to be written to the file.
close() Closes the stream after flushing it. After the stream has been closed, attempts to write or flush the stream
will throw an IOException .
All the BufferedWriter object methods mentioned here throw an IOException if an I/O error occurs.
Because a BufferedWriter object can only write strings or single characters, any numerical data must
be converted to a string before you can write it to the file. Because all the wrapper classes for the funda-
mental types provide toString() methods, this presents no particular difficulty.
Of course, strings are inherently variable in length so you need to consider how data written by a
BufferedWriter is going to be read. You either need to record information about the length of strings with-
in the data or make sure there are separator characters that you can use to determine where each data item
ends. Let's try an example.
TRY IT OUT: Writing a File Using a Buffered Writer
In this example, you write a series of strings to a file:
import java.io.*;
import java.nio.file.*;
import java.nio.charset.Charset;
public class WriterOutputToFile {
public static void main(String[] args) {
String[] sayings = {"A nod is as good as a wink to a blind
horse.",
"Least said, soonest mended.",
"There are 10 kinds of people in the world, "
+
"those that understand binary and those that
don't.",
"You can't make a silk purse out of a sow's
ear.",
"Hindsight is always twenty-twenty.",
"Existentialism has no future.",
"Those who are not confused are misinformed.",
"Better untaught that ill-taught."};
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("Sayings.txt");
try {
// Create parent directory if it doesn't exist
Files.createDirectories(file.getParent());
} catch(IOException e) {
System.err.println("Error creating directory: " +
file.getParent());
Search WWH ::




Custom Search