PrintWriter
is used to write data as text into files while FileOutputStream
is used to write in binary.
Consider
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(new File("data"));
for(int i=1;i<=10;++i)
pw.print(i);
pw.close();
}
}
Output :
12345678910
However, if I use FileOutputStream
I get binary data which is not readable in text.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream(new File("data")) ;
for(int i= 1; i<=10; ++i)
fos.write(i);
fos.close();
}
}
gives output:
Now, if I use PrintWriter
with FileOutputStream
, then I still get text data as shown below. Why? How does it become text and why?
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter( new FileOutputStream(new File("data")));
for(int i=1 ;i<=10;++i)
pw.print(i);
pw.close();
}
}
Output :
12345678910
****** Edit :***
Now consider , The case
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
PrintWriter pw = new PrintWriter( new DataOutputStream(new FileOutputStream(new File("data"))));
for(int i=1 ;i<=10;++i)
pw.print(i);
pw.close();
}
}
The output is still : 12345678910
According to JavaDocs :
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
So, Now If PrintWriter is sending bytes to DataOutputStream , how does the whole thing works ?
Files contain bytes. Always.
Characters are written into files by transforming characters into bytes, using an encoding. Many such encodings exist. For example, ASCII allows transforming 128 different characters to bytes. UTF-8 allows encoding any Unicode character to bytes. The two encodings, for example, transform the character '1' into the byte 49. '2' would be transformed into the byte 50.
When using a PrintWriter with a file name as argument, the PrintWriter actually opens a FileOuptutStream to write bytes to the file. When you write characters to the PrintWriter, the PrintWriter transforms characters to bytes using an encoding, and then write those bytes to the FileOutputStream, which writes the bytes to the file.
So, for example, if you use the following program:
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream(new File("data")) ;
for(int i = 49; i <= 58; ++i)
fos.write(i);
fos.close();
}
}
and then open the file with a text editor, you should see 123456789
in the file, because the code writes the byte representation (in ASCII or UTF8) of those characters directly.