本博客为子墨原创,转载请注明出处!http://blog.csdn.net/zimo2013/article/details/8885283
1.流转换实例
键盘录入: BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//键盘输入的字节流转为字符流
控制台输出:BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out);//将字符流转为字节流
2.流转换特点
(1).InputStreamReader从字节流-->字符流的转化,字符流和字节流之间的桥梁,其子类FileReader就是按照假定默认字符编码
(2).OutputStreamWriter从字符流-->字节流的转化,字符流和字节流之间的桥梁,其子类FileWriter就是按照假定默认字符编码
可以将FileWriter为OutputStreamWriter按默认编码GBK,FileReader为InputstreamReader按默认编码GBK
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("1.txt"), "GBK"));
提示:在进行流操作时,必须明确操作的源和目的,以便选取合适的类和操作对象!
/*
键盘-->控制台
Strawberry2013-5-4
*/
import java.io.*;
class SystemIn
{
public static void main(String[] args) throws IOException
{
//System.setIn(new FileInputStream("1.xtt"));//重新分配标准输入流,会认为System.in就是该流
//System.setOut(new PrintStream("1.xtt"));//重新分配标准输出流,会认为System.out 就是该输出流
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));
String str = null;
while(true)
{
str = bufr.readLine();
if(str.equals("over"))
break;
bufw.write(str.toUpperCase());
bufw.newLine();
bufw.flush();//此处必须进行刷新,因为写入的数据还在缓冲区中并未到达System.out,只有刷新后才能到达!
}
bufw.close();
bufr.close();
}
}
/*键盘-->文件()如果文件使用字符流存储,则不需要转化;如果以字节流存储则还需要使用OutputStreamWriter转化Strawberry2013-5-4*/import java.io.*;class SystemIn{public static void main(String[] args) throws IOException{BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("1.txt"));//如果以字节流存储以上!如果还是字符就不需要转化BufferedWriter(new FileWriter("1.txt"))String str = null;while(true){str = bufr.readLine();if(str.equals("over"))break;bufw.write(str.toUpperCase());bufw.newLine();bufw.flush();}bufw.close();bufr.close();}}