Java 中的轮换流:
非常有用,可以把一个字节流转换成字符流.
inputStreamReader, outputStreamReader
Demo_1:
import java.io.*; class Test { public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream("E:/eclipse projiect/TEST.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write("ni hao: 中国0123"); // 可以直接写字符串,中文也可以 System.out.println(osw.getEncoding()); // 按照默认的编码打印出来 osw.close(); osw = new OutputStreamWriter(new FileOutputStream("E:/eclipse projiect/TEST1.txt"), "ISO8859-1"); // 西方人订的西欧语言(或 latin-1) osw.write("Hello java"); System.out.println(osw.getEncoding()); osw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
GBK
ISO8859_1
TEST.txt 文件中的内容:ni hao: 中国0123
TEST1.txt 文件中的内容:Hello java
Demo_2:
import java.io.*; class Test { public static void main(String[] args) { InputStreamReader isr = new InputStreamReader(System.in); // 阻塞式方法,一直在等待 BufferedReader br = new BufferedReader(isr); // 同步方法 String s = null; try { s = br.readLine(); // 用其ReadLine()直接读取一行 while(s!=null){ if(s.equalsIgnoreCase("exit")){ break; } System.out.println(s.toUpperCase()); s = br.readLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
ni Hao
NI HAO
hao are you?
HAO ARE YOU?