InputStreamReaderDemo:
1 import java.io.*; 2 //为方便演示便省略异常处理。 3 class SystemDemo2 4 { 5 public static void main(String[] args)throws IOException 6 { 7 InputStream in = System.in; 8 InputStreamReader ins = new InputStreamReader(in); 9 BufferedReader bufr = new BufferedReader(ins); 10 while (true) 11 { 12 String s = bufr.readLine(); 13 System.out.println(s.toUpperCase()); 14 if (s.equals("over")) 15 { 16 break; 17 } 18 } 19 //bufr.close();爆出了无法访问的语句,可能是此缓存区最终的数据时键盘所以无需关闭流。 20 } 21 }
键盘的最常见写法:
BufferedReader bufr = new BufferedReader(new InputStream(System.in));
OutputStreamWriterDemo:
1 import java.io.*; 2 class OutputStreamReaderDemo 3 { 4 public static void main(String[] args) throws IOException 5 { 6 OutputStream out = System.out;//创建输出对象。 7 OutputStreamWriter outw = new OutputStreamWriter(out);//转换流对象,将需要转换的字节流作为参数传入转换流对象 8 BufferedWriter bufw = new BufferedWriter(outw);//缓冲区 9 bufw.write("afd");//调用写出方法 10 bufw.flush();//刷新 11 bufw.close();//关闭资源 12 // //三行变一行输出方式 13 // BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out)); 14 } 15 }
InputStream、OutputSreamDemo:(综合)
1 import java.io.*; 2 3 class TransStreamDemo 4 { 5 public static void main(String[] args) throws IOException 6 { 7 //获取键盘录入对象。 8 //InputStream in = System.in; 9 10 //将字节流对象转成字符流对象,使用转换流。InputStreamReader 11 //InputStreamReader isr = new InputStreamReader(in); 12 13 //为了提高效率,将字符流进行缓冲区技术高效操作。使用BufferedReader 14 15 //BufferedReader bufr = new BufferedReader(isr); 16 17 18 //键盘的最常见写法。 19 BufferedReader bufr = 20 new BufferedReader(new InputStreamReader(System.in)); 21 22 23 24 25 26 27 // OutputStream out = System.out; 28 // OutputStreamWriter osw = new OutputStreamWriter(out); 29 // BufferedWriter bufw = new BufferedWriter(osw); 30 BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out)); 31 32 33 34 35 String line = null; 36 37 while((line=bufr.readLine())!=null) 38 { 39 if("over".equals(line)) 40 break; 41 bufw.write(line.toUpperCase()); 42 bufw.newLine(); 43 bufw.flush(); 44 } 45 46 bufr.close(); 47 48 } 49 }
时间: 2024-10-24 13:35:04