Pregunta

Hi I have a bit of confusion about the stream to use to write in a text file

I had seen some example:

one use the PrintWriter stream

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fname)));

out.println(/*something to write*/);

out.close();

this instead use:

PrintStream out = new PrintStream(new FileOutputStream(fname));

out.println(/*something to write*/)

but which is the difference?both write in a file with the same result?

¿Fue útil?

Solución

PrintWriter is new as of Java 1.1; it is more capable than the PrintStream class. You should use PrintWriter instead of PrintStream because it uses the default encoding scheme to convert characters to bytes for an underlying OutputStream. The constructors for PrintStream are deprecated in Java 1.1. In fact, the whole class probably would have been deprecated, except that it would have generated a lot of compilation warnings for code that uses System.out and System.err.

Otros consejos

PrintWriter is for writing text, whereas PrintStream is for writing data - raw bytes. PrintWriter may change the encoding of the bytes to make handling text easier, so it might corrupt your data.

PrintWriter extends the class Writer, a class thinked to write characters, while PrintStream implements OutputStream, an interface for more generic outputs.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top