读取转换流--读取键盘录入中键盘录入一行数据并打印其大写,发现就是读一行数据的原理。
也就是readLine方法。
能不能直接使用readLine方法来完成键盘录入一行数据的读取呢?
readLine方法是字符流BufferedReader类中的方法。
而键盘录入的read方法是字节流InputStream的方法。
那么能不能将字节流转换成字符流再去使用字符流缓冲区的readLine方法呢。
public class TransStreamDemo { public static void main(String[] args) { // 获取键盘录入对象 InputStream is = System.in; // 将字节流对象转化为字符流对象,使用转换流InputStreamReader InputStreamReader isr = new InputStreamReader(is); // 为了提高效率,将字符串送入缓冲区,使用BufferedReader BufferedReader br = new BufferedReader(isr); String line = null; try { while ((line =br.readLine()) !=null) { if("over".equals(line)) break; System.out.println(line.toUpperCase()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
写入转换流--把字符流转换成字节流
public class TransStreamDemo2 { public static void main(String[] args) { // InputStream is=System.in; // InputStreamReader isr=new InputStreamReader(is); // BufferedReader br=new BufferedReader(isr); // 可简化为 // 这是最常用的读取键盘录入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // OutputStream os =System.out; // OutputStreamWriter osw = new OutputStreamWriter(os); // BufferedWriter bw = new BufferedWriter(osw); // 可简化为 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String line = null; try { while ((line = br.readLine()) != null) { if("over".equals(line)) break; // 打印大写 bw.write(line.toUpperCase()); bw.newLine(); bw.flush(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
流操作规律--吧键盘录入的数据存储到一个文件中
public class TransStreamDemo3 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:/out.txt"),"utf-8")); String line = null; while ((line = br.readLine()) != null) { if("over".equals(line)) break; bw.write(line); System.out.println("写入成功"); bw.newLine(); bw.flush(); } } }
将一个文件的数据打印在控制台上。
public class TransStreamDemo4 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("E:/out.txt"),"utf-8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String line = null; while((line = br.readLine()) != null){ bw.write(line); bw.newLine(); bw.flush(); } } }
时间: 2024-11-07 00:58:59