java – DataOutputStream#writeBytes(String)vs BufferedWriter #write(String)

I want to create an HTML file for my report You can use bufferedwriter #write (string) to create the content in the report

File f = new File("source.htm");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("Content");

Or use dataoutputstream#writebytes (string)

File f = new File("source.htm");
DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(f)); 
dosReport.wrtiteBytes("Content");

Is one better than the other? Why is that?

Solution

If you are writing text, you should use writer, which handles the conversion from Unicode characters (the internal representation of Java strings) to appropriate character encoding (such as UTF-8) DataOutputStream. Writebytes outputs only the lower 8 bits of each character in the string and completely ignores the upper 8 bits - this is equivalent to UTF-8 of ASCII characters with codes lower than 128 (U 007F and below), but it's almost certain of anything except ASCII

You should use outputstreamwriter instead of filewriter, so you can choose a specific encoding (filewriter always uses the default encoding of the platform, which varies by platform):

File f = new File("source.htm");
BufferedWriter bw = new BufferedWriter(
  new OutputStreamWriter(new FileOutputStream(f),"UTF-8"));
bw.write("Content");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>