----------------------------------
流操作的基本规律:
1,明确源和目的。
源:输入流。InputStream Reader
目的:输出流。OutputStream Writer。
2,操作的数据是否是纯文本。
是:字符流。
不是:字节流。
3,当体系明确后,在明确要使用哪个具体的对象。
通过设备来进行区分:
源设备:内存,硬盘。键盘
目的设备:内存,硬盘,控制台。
----------------------------------
字节流
一、字节流
InputStream
OutputStream
字节流缓冲区:
BufferedInputStream
BufferedOutputStream
实例一; import java.io.*; /* 字节流测试 InputStream OutputStream 注意:字节流写时,不需要刷新 */ class StreamTest { public static void main(String[] args) throws IOException { outputTest(); } //一次性读取完 public static void test_3() throws IOException { FileInputStream fis = new FileInputStream("Test.txt"); int len = fis.available(); byte[] temp = new byte[len]; fis.read(temp); System.out.print(new String(temp)); fis.close(); } //读取一个字节数组 public static void test_2() throws IOException { FileInputStream fis = new FileInputStream("Test.txt"); byte[] temp = new byte[1024]; int len = 0; while((len = fis.read(temp)) != -1) { System.out.print(new String(temp)); } fis.close(); } //读取一个打印一个 public static void test_1() throws IOException { FileInputStream fis = new FileInputStream("Test.txt"); int len = 0; while((len = fis.read()) != -1) { System.out.print((char)len + " "); } fis.close(); } //输出 public static void outputTest() throws IOException { FileOutputStream fos = new FileOutputStream("Test.txt"); fos.write("这是字符串".getBytes()); fos.close(); } } |