stream还是Reader Writer
stream是针对byte[]操作,针对于二进制文件操作。
Reader和Writer针对char操作,针对于文本文件操作。默认是用本机的编码方式写char ,如UTF-8和UTF-16和GB2312编码?
Reader和Writer是abstract类,不能直接用,一般用FileReader和FileWriter。?
如果采用具体编码,需要采用OutputStreamWriter。注意OutputStreamWriter的构造函数需要一个OutputStream的实例。?BufferedReader和另外PrintWriter可以支持一系列的print函数,也支持不同编码方式。?BufferedWriter针对普通Reader和Writer进行优化。?
PrintWriter?
PrintStream类似PrintWriter,提供了一系列print函数。例如System.out就是PrintStream。
?
编码方式?
OutputStreamWriter和PrintWriter都支持不同编码方式?
FileWriter只支持默认编码方式?
?
import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.util.Arrays;public class MyTest {public static void test1() throws IOException {FileOutputStream fos = new FileOutputStream("c:\\test.dat");byte[] buf = new byte[1024];Arrays.fill(buf, (byte) 'a');fos.write(buf);fos.close();}public static void test2() throws IOException {FileWriter writer = new FileWriter("c:\\test.txt");char c = 'A';String temp = "test";writer.write(c);writer.write(temp);writer.close();}public static void test3() throws IOException {OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("c:\\test.txt"),"utf-8");writer.append("北京理工大学");writer.close();}public static void test4() throws IOException {PrintWriter writer = new PrintWriter("c:\\1.txt", "utf-16");writer.append("北京理工大学");writer.close();}public static void main(String[] args) throws IOException {test4();System.out.println("OK");}}?