For the simplicity of writing a lot and also boring you guys I just have a question and if you guys can give me another example as well using maybe something simpler.
Here is the code
PrinterWriter w = new PrinterWriter(new FileWriter("test.txt"));
ok so the above works perfectly fine but so does this
FileWriter fw = new FileWriter("test.txt");
So does this work
PrintWriter w = PrintWriter(new File("test.text");
Ok so now all of these work but I am more concerned on why does the one in italics work.
I have read some of the documentation and have noticed that it takes a Writer
as the constructor argument, which FileWriter
is an extension of.
But if that is true then why does this not work (or maybe it does)
FileWriter fw = FileWriter(new PrintWriter("test.txt));
I have not yet confirmed if this works but I do not see what this would do anyways ( the others make sense ) but can anyone just explain even the slightest bit of information?
Java uses the Decorator pattern to provide specialized combinations of Writer/Stream
Writer
an object you can write characters to PrintWriter
specialized Writer
that provides formating options, like linebreaks (eg println()
) or `printf`` aso OutputStream
an object to write bytes to So:
A FileWriter("test.txt")
is an object you can write characters to, that are written to a file.
A PrintWriter(new FilteWriter("test.txt"))
is an object that provides formatting options, that writes characters to an object that writes to a file.
A PrintWriter(new File("test.txt"))
is semantically the same, a writer with formatting options that writes characters to a file. (just without an extra step)
FileWriter fw = FileWriter(new PrintWriter("test.txt));
does not compile.
Two other common Writers are the BufferedWriter
StringWriter
. The BufferedWriter
o ptimizes for larger chunks of writes, it only writes to the underlying Writer
if the buffer is full or flushed. StringWriter
is the basic "in memory" implementation that appends to a String.
With that: BufferedWriter( new PrintWriter( new FileWriter("test.txt")));"
a chunk based writer with no formatting options, that uses a PrintWriter
and FileWriter
to write characters to a file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.