字符流使用默认缓冲区和编码器,编码集是系统码无法调整
java提供了转换流,自己编写字节流读取数据,通过转换流 换为字符流,其中可以手动指定码表。
InputStreamReader 、 OutputStreamWriter
public static void main(String[] args) throws Exception {
//字节流
FileInputStream in=new FileInputStream("D:\\a.txt");
FileOutputStream out=new FileOutputStream("D:\\a2.txt");
//转换流----->字符流
InputStreamReader reader=new InputStreamReader(in,"utf-8");
OutputStreamWriter writer=new OutputStreamWriter(out,"utf-8"); //需要转换别的可以修改编码
int i=0;
char[] cs=new char[1024];
while((i=reader.read(cs))!=-1) {
writer.write(cs,0,i); //记得0,i
}
writer.close();
reader.close();
System.out.println("结束");
}
系统流
System.out/in/err…
public static void main(String[] args) throws Exception {
System.out.println("asd");
System.err.println("asd");
}
err 和 out 不同的是颜色
可以写到文本里,在控制台上不显示
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(new FileOutputStream("D:\\a.txt")));
System.setErr(new PrintStream(new FileOutputStream("D:\\a2.txt")));
System.out.println("asd");
System.err.println("asd");
}
System.in
用法一(只能打印一个字符):
InputStream in=System.in;
System.out.println((char)(in.read()));
用法二(标准的用法,能打印一行):
public static void main(String[] args) throws Exception {
BufferedReader in =new BufferedReader (new InputStreamReader(System.in) );
String str=in.readLine();
System.out.println(str);
}
System.setin
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("D:\\a.txt"));
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String str=null;
while((str=reader.readLine())!=null) {
System.out.println(str);
}
}