1、缓冲流
缓冲流,也叫高效流,是对四个基本的FileXxx流的增强,所以也是4个流
字节缓冲流:
BufferedInputStream BufferedOutputStream
字符缓冲流:
BufferedReader Bufferedwriter
基本原理:在创建对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率
字节缓冲流:
BufferedInputStream(InputStream In):创建一个新的缓冲输入流
BufferedOutputStream(OutputStream out):创建一个新的缓冲输出流
一次读取一个字节:
public class BufferedDemo {public static void main(String[] args) throws FileNotFoundException {BufferedInputStream bis = null;BufferedOutputStream bos = null;// 创建流对象try {bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));// 读写数据int b;while ((b = bis.read()) != -1) {bos.write(b);}} catch (IOException e) {e.printStackTrace();} finally{if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (bos != null) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}}}}
一次读取一个字节数组:
public class BufferedDemo {public static void main(String[] args) throws FileNotFoundException {BufferedInputStream bis = null;BufferedOutputStream bos = null;// 创建流对象try {bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));// 读写数据int len;byte[] bytes = new byte[8*1024];while ((len = bis.read(bytes)) != -1) {bos.write(bytes, 0 , len);}} catch (IOException e) {e.printStackTrace();} finally{if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (bos != null) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}}}}
字符缓冲流:
BufferedReader(Reader in):创建一个新的缓冲输入流
String readLine():一次读取一行文字
BufferedWriter(Writer out):创建一个新的缓冲输出流
void newLine():写一行行分隔符,由系统属性定义符号
public class BufferedReaderDemo {public static void main(String[] args) throws IOException {// 创建流对象BufferedReader br = new BufferedReader(new FileReader("in.txt"));// 定义字符串,保存读取的一行文字String line = null;// 循环读取,读取到最后返回nullwhile ((line = br.readLine())!=null) {System.out.print(line);System.out.println("------");}// 释放资源br.close();}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~public class BufferedWriterDemo throws IOException {public static void main(String[] args) throws IOException {// 创建流对象BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));for(int i = 0 ; i < 5 ; i++){// 写出数据bw.write("HelloWorld!");bw.newLine();}// 释放资源bw.close();}}
2、转换流
字符编码:
按照某种规则,将字符存储到计算机中称为编码
将储存在计算中的二进制数按照某种规则解析显示出来称为解码
编码:字符(看的懂的)==============》字节(看不懂的)
解码:字节(看不懂的)==============》字符(看的懂的)
字符编码就是一套自然语言 的字符与二进制之间的对应规则
编码表:生活中文字和计算机中二进制的对应规则
字符集:
也叫作编码表,是一个系统所支持的所有字符的集合,包括各国家文字,标点符号,图形符号,数字等
常见字符集:
ASCII字符集:
基于拉丁字母的一套电脑编码系统
ISO-8859-1字符集:
拉丁码表,别名Latin-1,用于显示欧洲使用的语言
使用单字节编码,兼容ASCII
GBxxx字符集:
GB就是国标:用于显示中文而设计的一套字符
GB2312:简体中文码表,两个大于127的字符表示一个汉字,大约有7000简体汉字
GBK:最常用的中文码表,是上一个的扩展,双字节编码,收录哟21003个汉字
GB18030:最新的中文码表,共收录70244个,采用多字节编码,每个字由1,2或4个字节组成
Unicode字符集:
为表达任意语言的任意字符而设计,是业界的一种标准,也成为统一码,标准万国码
最多使用4个字节的数字来表达每个字母,符号,或者文字,有utf8,utf16,utf32
UTF-8:最为常用
1、128个US-ASCII字符,只需要一个字节编码
2、拉丁文等字符,需要两个字节编码
3、大部分常用字(含中文),使用三个字节编码
4、其他极少适用Unicode辅助字符,使用四字节编码
编码引出的问题:
在IDEA中,读取项目中的文本文件,由于IDEA的设置,默认为UTF8,但是当读取Windows系统创建(默认为:GBK)的文本文件时,就会出现乱码
InputStreamReader:
是字节流到字符流的桥梁,他读取字节,并使用指定字符集将其解码为字符
InputStreamReader(InputStream in):创建一个使用默认字符集的输入流
InputStreamReader(InputStream in,String charsetName):创建一个指定字符集的输入流
InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");
指定编码读取文件:
public class ReaderDemo2 {public static void main(String[] args) throws IOException {// 定义文件路径,文件为gbk编码String FileName = "E:\\file_gbk.txt";// 创建流对象,默认UTF8编码InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName)); // utf-8// 创建流对象,指定GBK编码InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");// 定义变量,保存字符int read;// 使用默认编码字符流读取,乱码while ((read = isr.read()) != -1) {System.out.print((char)read); // ��Һ�}isr.close();// 使用指定编码字符流读取,正常解析while ((read = isr2.read()) != -1) {System.out.print((char)read);// 大家好}isr2.close();}}
OutputStreamWriter:
是字符流到字节流的桥梁,使用指定的字符集将字符编码为字节
OutputStreamWriter(OutputStream out):创建一个使用默认字符集的字符输出流
OutputStreamWriter(OutputStream out,String charsetName):创建一个指定字符集的字符输出流
OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");
指定编码写出数据:
public class OutputDemo {public static void main(String[] args) throws IOException {// 定义文件路径String FileName = "E:\\out.txt";// 创建流对象,默认UTF8编码OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));// 写出数据osw.write("你好"); // 保存为6个字节osw.close();// 定义文件路径String FileName2 = "E:\\out2.txt";// 创建流对象,指定GBK编码OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");// 写出数据osw2.write("你好");// 保存为4个字节osw2.close();}}
将GBK编码文本文件,转为UTF8编码文本文件:
public class TransDemo {public static void main(String[] args) {// 1.定义文件路径String srcFile = "file_gbk.txt";String destFile = "file_utf8.txt";// 2.创建流对象// 2.1 转换输入流,指定GBK编码InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");// 2.2 转换输出流,默认utf8编码Output eamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile));// 3.读写数据// 3.1 定义数组char[] cbuf = new char[1024];// 3.2 定义长度int len;// 3.3 循环读取while ((len = isr.read(cbuf))!=-1) {// 循环写出osw.write(cbuf,0,len);}// 4.释放资源osw.close();isr.close();}}
3、序列化流
Java提供一种都对象序列化的机制,用一个字节序列可以表示一个对象,该字节序列包含该对象的数据,对象的类型和对象中存储的属性等信息
反之,将该字节序列从文件中读取出来,重构对象,对他反序列化
OBjectOutputStream:
将Java对象的原始数据类型写出到文件,实现对象的持久化储存
ObjectOutputStream(OutputStream out):序列化输出流
void writerObject(Object obj):将指定对象写出
一个对象想要序列化,必须满足的两个条件:
1、该了必须实现Serializable接口
2、该类的所有属性必须是可序列化的,如果有一个属性不需要可序列化,则该属性必定著名是瞬态的,使用transient关键字修饰
public class Employee implements java.io.Serializable {public String name;public String address;public transient int age; // transient瞬态修饰成员,不会被序列化public void addressCheck() {System.out.println("Address check : " + name + " -- " + address);}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~public class SerializeDemo{public static void main(String [] args) {Employee e = new Employee();e.name = "zhangsan";e.address = "beiqinglu";e.age = 20;try {// 创建序列化流对象ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));// 写出对象out.writeObject(e);// 释放资源out.close();fileOut.close();System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。} catch(IOException i) {i.printStackTrace();}}}
ObjectInputStream:
反序列化流,将序列化的原始数据恢复为对象
ObjecInputStream(InputStream out):反序列化输入流
void readObject(Object obj):读取一个对象
public class DeserializeDemo {public static void main(String [] args) {Employee e = null;try {// 创建反序列化流FileInputStream fileIn = new FileInputStream("employee.txt");ObjectInputStream in = new ObjectInputStream(fileIn);// 读取一个对象e = (Employee) in.readObject();// 释放资源in.close();fileIn.close();}catch(IOException i) {// 捕获其他异常i.printStackTrace();return;}catch(ClassNotFoundException c) {// 捕获 类找不到 异常System.out.println("Employee class not found");c.printStackTrace();return;}// 无异常,直接打印输出System.out.println("Name: " + e.name); // zhangsanSystem.out.println("Address: " + e.address); // beiqingluSystem.out.println("age: " + e.age); // 0}}
案例·序列化集合:
1、把若干学生对象,保存到集合中
2、把集合序列化
3、反序列化读取时,只需要读取一次,转化为集合类型
4、遍历集合,打印所有的学生信息
public class SerTest {public static void main(String[] args) throws Exception {// 创建 学生对象Student student = new Student("老王", "laow");Student student2 = new Student("老张", "laoz");Student student3 = new Student("老李", "laol");ArrayList<Student> arrayList = new ArrayList<>();arrayList.add(student);arrayList.add(student2);arrayList.add(student3);// 序列化操作// serializ(arrayList);// 反序列化ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt"));// 读取对象,强转为ArrayList类型ArrayList<Student> list = (ArrayList<Student>)ois.readObject();for (int i = 0; i < list.size(); i++ ){Student s = list.get(i);System.out.println(s.getName()+"--"+ s.getPwd());}}private static void serializ(ArrayList<Student> arrayList) throws Exception {// 创建 序列化流ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));// 写出对象oos.writeObject(arrayList);// 释放资源oos.close();}}
4、打印流
字节打印流:PrintStream
字符打印流:PrintWriter
特点:
1、只负责输出数据,不负读取数据
2、永远不会抛出IOException
3、有自己的特有方法
感觉没什么记的
5、Properties集合
1、是一个Map体系的集合类
2、可以保存到流中或者从流中加载
3、属性列表中的每个建及其对象的值都是一个字符串
基本使用:
public class PropertiesDemo01 {public static void main(String[] args) {//创建集合对象// Properties<String,String> prop = new Properties<String,String>(); //错误Properties prop = new Properties();//存储元素prop.put("itfxp001", "林青霞");prop.put("itfxp002", "张曼玉");prop.put("itfxp003", "王祖贤");//遍历集合Set<Object> keySet = prop.keySet();for (Object key : keySet) {Object value = prop.get(key);System.out.println(key + "," + value);}}}
Object setProperty(Streing key , Steing value):设置集合的键和值。底层调用Hashset方法put
Object getProperty(Streing key):通过键获取值
Set
public class PropertiesDemo02 {public static void main(String[] args) {//创建集合对象Properties prop = new Properties();//Object setProperty(String key, String value):设置集合的键和值,都是String类型,底层调用Hashtable方法putprop.setProperty("itfxp001", "林青霞");/*Object setProperty(String key, String value) {return put(key, value);}Object put(Object key, Object value) {return map.put(key, value);}*/prop.setProperty("itfxp002", "张曼玉");prop.setProperty("itfxp003", "王祖贤");//String getProperty(String key):使用此属性列表中指定的键搜索属性// System.out.println(prop.getProperty("itheima001"));// System.out.println(prop.getProperty("itheima0011"));// System.out.println(prop);//Set<String> stringPropertyNames():从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串Set<String> names = prop.stringPropertyNames();for (String key : names) {// System.out.println(key);String value = prop.getProperty(key);System.out.println(key + "," + value);}}}
Properties和IO流相结合的方法:
void load(InputStream in):从输入字节流读取属性列表(键和元素对)
void load(Reader reader):从输入字符流读取属性列表(键和元素对)
void store(OutputStream out,String comments):将此属性列表(键和元素对)写入此Properties表中,以适合于使用load(inputStream)方法的格式写入输出字符流
void store(Writer writer,String comments):将此属性列表(键和元素对)写入此Properties表中,以适合于使用load(Reader)方法的格式写入输出字符流
public class PropertiesDemo03 {public static void main(String[] args) throws IOException {//把集合中的数据保存到文件// myStore();//把文件中的数据加载到集合myLoad();}private static void myLoad() throws IOException {Properties prop = new Properties();//void load(Reader reader):FileReader fr = new FileReader("myOtherStream\\fw.txt");prop.load(fr);fr.close();System.out.println(prop);}private static void myStore() throws IOException {Properties prop = new Properties();prop.setProperty("itfxp001","林青霞");prop.setProperty("itfxp002","张曼玉");prop.setProperty("itfxp003","王祖贤");//void store(Writer writer, String comments):FileWriter fw = new FileWriter("myOtherStream\\fw.txt");prop.store(fw,null);fw.close();}}
IO流扩展
commons-io:
一款io流的工具,封装了很多处理io流和文件的方法,可以大大简化处理io流和操作代码
主要分为,工具类,尾端类,迭代器,文件过滤器等
工具类:使用静态方法执行共同任务
输入:用于InputStream和Reader实现
输出:用户OutputStream和Writer实现
过滤器:各种文件过滤器实现
比较器:各种文件的java.util.Comparator实现
文件监听器:监听文件系统事件的组件
常用工具类:
1、FileUtils
2、IoUtils
3、FilenameUtils
4、FileSystemUtils
注意:首先应该先导包
FileUtils:
提供文件操作(移动文件,读取文件,检查文件是否存在等等)的方法
String readFileToString(File file):读取文件内容,返回一个String
void writeStringToFile(file,data):将内容字符串data写入到file中
void copyDirectoryToDirectory(srcDir,srcDir):文件夹复制
void copyFile(file,file):文件复制
void copyFileToDirectory(file,srcDir):将文件复制到文件夹
FilenameUtils:
这个工具类主要用来处理文件名(包含文件路径)
String getExtension(String fileName):获取文件的扩展名
String getName(String fileName):获取文件名带扩展名
String getBaseName(String fileName):获取文件名
boolean isExtension(String fileName,String extension):判断fileName是否是ext后缀名
IOUtils:
包含处理读,写,复制的工具方法
int copy(InputStream in ,OutputStream out):字节流复制文件
int copy(Reader input , Writer output):字符流复制文件
