oug*_*ugh 33 java filewriter printwriter
Java中的PrintWriter和FileWriter是否相同,无论使用哪一个?到目前为止,我使用了两者,因为他们的结果是一样的.是否有一些特殊情况下更喜欢一个而不是另一个?
public static void main(String[] args) {
File fpw = new File("printwriter.txt");
File fwp = new File("filewriter.txt");
try {
PrintWriter pw = new PrintWriter(fpw);
FileWriter fw = new FileWriter(fwp);
pw.write("printwriter text\r\n");
fw.write("filewriter text\r\n");
pw.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
kam*_*aci 28
根据coderanch.com,如果我们结合我们得到的答案:
FileWriter是IO的字符表示.这意味着它可以用来写字符.在内部,FileWriter将使用底层操作系统的默认字符集,并将字符转换为字节并将其写入磁盘.
PrintWriter和FileWriter.
相似
差异
PrintStream和OutputStream之间的区别:与上面的解释类似,只需用byte替换字符即可.
PrintWriter有以下方法:
close()
flush()
format()
printf()
print()
println()
write()
Run Code Online (Sandbox Code Playgroud)
和构造函数是:
File (as of Java 5)
String (as of Java 5)
OutputStream
Writer
Run Code Online (Sandbox Code Playgroud)
而FileWriter有以下方法:
close()
flush()
write()
Run Code Online (Sandbox Code Playgroud)
和构造函数是:
File
String
Run Code Online (Sandbox Code Playgroud)
链接:http://www.coderanch.com/t/418148/java-programmer-SCJP/certification/Information-PrintWriter-FileWriter
这两个都在FileOutputStream
内部使用:
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
Run Code Online (Sandbox Code Playgroud)
但主要的区别是PrintWriter提供了特殊的方法:
将对象的格式化表示打印到文本输出流.此类实现PrintStream中的所有打印方法.它不包含写入原始字节的方法,程序应使用未编码的字节流.
与PrintStream类不同,如果启用了自动刷新,则只有在调用println,printf或format方法之一时才会执行,而不是每当输出换行符时.这些方法使用平台自己的行分隔符概念而不是换行符.