过滤流又称流的装配:缓存作用,用于装配文件磁盘、网络设备、终端等读写开销大的节点流,提高读写性能
使用类:BufferedInputStream
和 BufferedOutputStream
DataInputStream di = new DataInputStream(new BufferedInputStream(new FileInputStream(f))) DataOutputStream do = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)))
BufferedReader
的使用作用:用于缓存字符流,可以一行一行的读
import java.io.*; public class inDataSortMaxMinIn { public static void main(String args[]) { try{ BufferedReader keyin = new BufferedReader(new InputStreamReader(System.in)); String c1; int i=0; int[] e = new int[10]; while(i<10){ try{ c1 = keyin.readLine(); e[i] = Integer.parseInt(c1); i++; } catch(NumberFormatException ee){ System.out.println("请输入正确的数字!"); } } } catch(Exception e){ System.out.println("系统有错误"); }}}
DataInputStream 和 DataOutputStream
的使用作用: 可从字节流中写入、读取Java基本数据类型,不依赖于机器的具体数据类型,方便存储和恢复数据
import java.io.*; public class DataStream { public static void main(String[] args)throws Exception{ try { DataOutputStream d=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("test.txt"))); d.writeInt(3);//写入整型 d.writeDouble(3.14);//写入浮点型 d.writeUTF(“hello”);//写入字符串 d.close(); DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("test.txt"))); System.out.println(dis.readInt()); //读取整型,输出3 System.out.println(dis.readDouble()); //读取浮点型,输出3.14 System.out.println(dis.readUTF()); //读取字符串,输出hello dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
PrintWriter
的使用作用:可以向该字符流中写入Java基本数据类型,用于包装输出字符流类对象
import java.io.*; public class PrintWrit { public static void main(String[] args)throws Exception{ PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.txt"))); out.println(“hello”); //写入字符串 out.println(3); //写入整型 out.close(); //关闭流,系统自动将缓冲区内容flush } }