第19天-18-IO流(流操作规律 - 1)
明确数据流的"源和目的"
源, 输入流: InputStream/Reader
目的, 输出流: OutputStream/Writer
明确操作的数据是否是纯文本
是, 字符流
不是, 字节流
通过设备来区分要使用哪个具体的类
源设备: 内存/硬盘/键盘
目的设备: 内存/硬盘/控制台
附录
是否需要进行缓冲:
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
是否需要进行 "字符 - 字节" 以及charset的转换:
例如OutputStreamWriter(OutputStream out, String charsetName)
第19天-19-IO流(流操作规律 - 2)
package bxd; import java.io.*; public class TransStreamDemo2 { public static void main(String[] args) throws IOException { method_5(); } // 将一个文本文件中的数据存储到另外一个文件中 public static void method_1() throws IOException { BufferedReader bufr = new BufferedReader(new FileReader("s.txt")); BufferedWriter bufw = new BufferedWriter(new FileWriter("d.txt")); String line; while ((line = bufr.readLine()) != null) { bufw.write(line); bufw.newLine(); bufw.flush(); } bufr.close(); bufw.close(); } // 将键盘录入的数据保存到一个文件中 public static void method_2() throws IOException { BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufw = new BufferedWriter(new FileWriter("d.txt")); String line; while ((line = bufr.readLine()) != null) { if ("over".equals(line)) break; bufw.write(line); bufw.newLine(); bufw.flush(); } bufr.close(); bufw.close(); } // 将键盘录入的数据保存到一个文件中, 并可以自定义目标文件的字符编码. public static void method_3() throws IOException { BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d.txt"), "utf-8")); String line; while ((line = bufr.readLine()) != null) { if ("exit".equals(line)) break; bufw.write(line); bufw.newLine(); bufw.flush(); } bufr.close(); bufw.close(); } // 练习1: 将一个图片文件中的数据存储到另外一个文件中 public static void method_4() throws IOException { BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("1.png")); BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("2.png")); int by; while ((by = bufis.read()) != -1) { bufos.write(by); } bufis.close(); bufos.close(); } // 练习2: 将一个文本文件的数据输出到控制台 public static void method_5() throws IOException { BufferedReader bufr = new BufferedReader(new FileReader("s.txt")); BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out)); String line; while ((line = bufr.readLine()) != null) { bufw.write(line); bufw.newLine(); bufw.flush(); } bufr.close(); bufw.close(); } }