JavaSE(字符流、IO资源的处理、属性集、ResourceBundle工具类、缓冲流、转换流、序列化、打印流、装饰设计模式、commons-io工具包)

JavaSE

字符流

字符输入流【Reader】

字符输入流Reader类的概述

java.io.Reader抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。

字符输入流Reader类的常用方法

  • public void close() :关闭此流并释放与此流相关联的任何系统资源。
  • public int read(): 从输入流读取一个字符。
  • public int read(char[] cbuf): 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。

FileReader类

FileReader类的概述

java.io.FileReader类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

FileReader类的构造方法

  • FileReader(File file): 创建一个新的 FileReader ,给定要读取的File对象。
  • FileReader(String fileName): 创建一个新的 FileReader ,给定要读取的文件的名称。

当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。

  • 示例代码:
public class FileReaderConstructor throws IOException{
    public static void main(String[] args) {
   	 	// 使用File对象创建流对象
        File file = new File("a.txt");
        FileReader fr = new FileReader(file);
      
        // 使用文件名称创建流对象
        FileReader fr = new FileReader("b.txt");
    }
}

FileReader类读取数据

  1. 读取字符read方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1,循环读取,代码使用演示:
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// 使用文件名称创建流对象
       	FileReader fr = new FileReader("read.txt");
      	// 定义变量,保存数据
        int b ;
        // 循环读取
        while ((b = fr.read())!=-1) {
            System.out.println((char)b);
        }
		// 关闭资源
        fr.close();
    }
}

小贴士:虽然读取了一个字符,但是会自动提升为int类型。

  1. 使用字符数组读取read(char[] cbuf),每次读取多个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1 ,代码使用演示:
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// 使用文件名称创建流对象
       	FileReader fr = new FileReader("read.txt");
      	// 定义变量,保存有效字符个数
        int len ;
        // 定义字符数组,作为装字符数据的容器
        char[] cbuf = new char[2];
        // 循环读取
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf));
        }
		// 关闭资源
        fr.close();
    }
}

获取有效的字符改进,代码使用演示:

public class FISRead {
    public static void main(String[] args) throws IOException {
      	// 使用文件名称创建流对象
       	FileReader fr = new FileReader("read.txt");
      	// 定义变量,保存有效字符个数
        int len ;
        // 定义字符数组,作为装字符数据的容器
        char[] cbuf = new char[2];
        // 循环读取
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf,0,len));
        }
    	// 关闭资源
        fr.close();
    }
}

字符输出流【Writer】

字符输出流Writer类的概述

java.io.Writer抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。

字符输出流Writer类的常用方法

  • public abstract void close() :关闭此输出流并释放与此流相关联的任何系统资源。
  • public abstract void flush() :刷新此输出流并强制任何缓冲的输出字符被写出。
  • public void write(int c) :写出一个字符。
  • public void write(char[] cbuf):将 b.length字符从指定的字符数组写出此输出流。
  • public abstract void write(char[] b, int off, int len) :从指定的字符数组写出 len字符,从偏移量 off开始输出到此输出流。
  • public void write(String str) :写出一个字符串。
  • public void write(String str,int off,int len) :写出一个字符串的一部分。

知识点–FileWriter类

FileWriter类的概述

java.io.FileWriter类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

FileWriter类的构造方法

  • FileWriter(File file): 创建一个新的 FileWriter,给定要读取的File对象。
  • FileWriter(String fileName): 创建一个新的 FileWriter,给定要读取的文件的名称。
  • FileWriter(File file,boolean append): 创建一个新的 FileWriter,给定要读取的File对象。
  • FileWriter(String fileName,boolean append): 创建一个新的 FileWriter,给定要读取的文件的名称。

当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream。

  • 示例代码:
public class FileWriterConstructor {
    public static void main(String[] args) throws IOException {
   	 	// 使用File对象创建流对象
        File file = new File("a.txt");
        FileWriter fw = new FileWriter(file);
      
        // 使用文件名称创建流对象
        FileWriter fw = new FileWriter("b.txt");
    }
}

FileWriter类写出数据

  1. 写出字符write(int b) 方法,每次可以写出一个字符数据,代码使用演示:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用文件名称创建流对象
        FileWriter fw = new FileWriter("fw.txt");     
      	// 写出数据
      	fw.write(97); // 写出第1个字符
      	fw.write('b'); // 写出第2个字符
      	fw.write('C'); // 写出第3个字符
      	fw.write(30000); // 写出第4个字符,中文编码表中30000对应一个汉字。
      
      	/*
        【注意】关闭资源时,与FileOutputStream不同。
      	 如果不关闭,数据只是保存到缓冲区,并未保存到文件。
        */
        // fw.close();
    }
}
输出结果:
abC田

小贴士:

  1. 虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。
  2. 未调用close方法,数据只是保存到了缓冲区,并未写出到文件中。
  1. 写出字符数组write(char[] cbuf)write(char[] cbuf, int off, int len) ,每次可以写出字符数组中的数据,用法类似FileOutputStream,代码使用演示:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用文件名称创建流对象
        FileWriter fw = new FileWriter("fw.txt");     
      	// 字符串转换为字节数组
      	char[] chars = "XXX".toCharArray();
      
      	// 写出字符数组
      	fw.write(chars); // XXX
        
		// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
        fw.write(b,2,2); 
      
      	// 关闭资源
        fos.close();
    }
}
  1. 写出字符串write(String str)write(String str, int off, int len) ,每次可以写出字符串中的数据,更为方便,代码使用演示:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用文件名称创建流对象
        FileWriter fw = new FileWriter("fw.txt");     
      	// 字符串
      	String msg = "XXX";
      
      	// 写出字符数组
      	fw.write(msg); //XXX
      
		// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
        fw.write(msg,2,2);
      	
        // 关闭资源
        fos.close();
    }
}
  1. 续写和换行:操作类似于FileOutputStream。
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用文件名称创建流对象,可以续写数据
        FileWriter fw = new FileWriter("fw.txt"true);     
      	// 写出字符串
        fw.write("XX");
      	// 写出换行
      	fw.write("\r\n");
      	// 写出字符串
  		fw.write("XXX");
      	// 关闭资源
        fw.close();
    }
}

小贴士:字符流,只能操作文本文件,不能操作图片,视频等非文本文件。

当单纯读或者写文本文件时 使用字符流 其他情况使用字节流

关闭和刷新

因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中。但是关闭的流对象,是无法继续写出数据的。如果既想写出数据,又想继续使用流,就需要flush 方法了。

  • flush :刷新缓冲区,流对象可以继续使用。
  • close :关闭流,释放系统资源。关闭前会刷新缓冲区。

示例代码:

public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用文件名称创建流对象
        FileWriter fw = new FileWriter("fw.txt");
        // 写出数据,通过flush
        fw.write('刷'); // 写出第1个字符
        fw.flush();
        fw.write('新'); // 继续写出第2个字符,写出成功
        fw.flush();
      
      	// 写出数据,通过close
        fw.write('关'); // 写出第1个字符
        fw.close();
        fw.write('闭'); // 继续写出第2个字符,【报错】java.io.IOException: Stream closed
        fw.close();
    }
}

小贴士:即便是flush方法写出了数据,操作的最后还是要调用close方法,释放系统资源。

IO资源的处理

JDK7前处理

之前的复习笔记中一直把异常抛出,而实际开发中并不能这样处理,建议使用try...catch...finally 代码块,处理异常部分,代码使用演示:

public class HandleException1 {
    public static void main(String[] args) {
      	// 声明变量
        FileWriter fw = null;
        try {
            //创建流对象
            fw = new FileWriter("fw.txt");
            // 写出数据
            fw.write("XXX"); //XXX
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

JDK7的处理

还可以使用JDK7优化后的try-with-resource 语句,该语句确保了每个资源在语句结束时关闭。所谓的资源(resource)是指在程序完成后,必须关闭的对象。

格式:

try (创建流对象语句,如果多个,使用';'隔开) {
	// 读写数据
} catch (IOException e) {
	e.printStackTrace();
}

示例代码:

public class HandleException2 {
    public static void main(String[] args) {
      	// 创建流对象
        try ( FileWriter fw = new FileWriter("fw.txt"); ) {
            // 写出数据
            fw.write("XXX"); //XXX
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

属性集

Properties类

Properties类的概述

java.util.Properties 继承于Hashtable ,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,System.getProperties 方法就是返回一个Properties对象。

Properties类的构造方法

public Properties() :创建一个空的属性列表。

Properties类存储方法

  • public Object setProperty(String key, String value) : 保存一对属性。
  • public String getProperty(String key) :使用此属性列表中指定的键搜索属性值。
  • public Set<String> stringPropertyNames() :所有键的名称的集合。
public class ProDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 创建属性集对象
        Properties properties = new Properties();
        // 添加键值对元素
        properties.setProperty("filename", "a.txt");
        properties.setProperty("length", "209385038");
        properties.setProperty("location", "D:\\a.txt");
        // 打印属性集对象
        System.out.println(properties);
        // 通过键,获取属性值
        System.out.println(properties.getProperty("filename"));
        System.out.println(properties.getProperty("length"));
        System.out.println(properties.getProperty("location"));

        // 遍历属性集,获取所有键的集合
        Set<String> strings = properties.stringPropertyNames();
        // 打印键值对
        for (String key : strings ) {
          	System.out.println(key+" -- "+properties.getProperty(key));
        }
    }
}
输出结果:
{filename=a.txt, length=209385038, location=D:\a.txt}
a.txt
209385038
D:\a.txt
filename -- a.txt
length -- 209385038
location -- D:\a.txt

Properties类与流相关的方法

  • public void load(InputStream inStream): 从字节输入流中读取键值对。

参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了。文本数据格式:

filename=a.txt
length=209385038
location=D:\a.txt

加载示例代码:

public class ProDemo2 {
    public static void main(String[] args) throws FileNotFoundException {
        // 创建属性集对象
        Properties pro = new Properties();
        // 加载文本中信息到属性集
        pro.load(new FileInputStream("read.txt"));
        // 遍历集合并打印
        Set<String> strings = pro.stringPropertyNames();
        for (String key : strings ) {
          	System.out.println(key+" -- "+pro.getProperty(key));
        }
     }
}
输出结果:
filename -- a.txt
length -- 209385038
location -- D:\a.txt

小贴士:文本中的数据,必须是键值对形式,可以使用空格、等号、冒号等符号分隔。

ResourceBundle工具类

ResourceBundle类的介绍

Properties工具类,它能够读取资源文件,当资源文件是以.properties结尾的文件时,可以使用JDK提供的另外一个工具类ResourceBundle来对文件进行读取,使得操作更加简单。

java.util.ResourceBundle它是一个抽象类,可以使用它的子类PropertyResourceBundle来读取以.properties结尾的配置文件。

ResourceBundle类对象的创建

在ResourceBundle类中提供了一个静态方法,用于获得它的子类对象(抽象类不能创建对象!)。

// 使用指定的基本名称,默认语言环境和调用者的类加载器获取资源包。  
static ResourceBundle getBundle(String baseName); 

注意:

​ ①properties配置文件需要放置在类的根路径src下面

​ ②给定参数只需要配置文件的名称,不要扩展名。

public class TestResourceBundle {
    public static void main(String[] args) {
        // 获得ResourceBundle类的对象(properties文件要放置在src目录下,给定参数只要文件名称,不要扩展名!)
        ResourceBundle bundle = ResourceBundle.getBundle("XXX");// 父类引用指向子类对象(多态)
        System.out.println(bundle);
    }
}

ResourceBundle读取配置文件操作

ResourceBundle类提供了一个getString(String key)方法用于读取配置文件中指定key的值。

String getString(String key) 从此资源束或其父项之一获取给定密钥的字符串。  

示例代码:

public class TestResourceBundle {
    public static void main(String[] args) {
        // 获得ResourceBundle类的对象(properties文件要放置在src目录下,给定参数只要文件名称,不要扩展名)
        ResourceBundle bundle = ResourceBundle.getBundle("data");
        System.out.println(bundle);

        // 读取指定key(username)的值
        String username = bundle.getString("username");
        System.out.println(username);

        // 读取指定key(password)的值
        String password = bundle.getString("password");
        System.out.println(password); 
    }
}

缓冲流

缓冲流的概述

作为IO流的入门,要见识一些更强大的流。比如能够高效读写的缓冲流,能够转换编码的转换流,能够持久化存储对象的序列化流等等。这些功能更为强大的流,都是在基本的流对象基础之上创建而来的,就像穿上铠甲的武士一样,相当于是对基本流对象的一种增强。

缓冲流,也叫高效流,是对4个基本的FileXxx 流的增强,所以也是4个流,按照数据类型分类:

  • 字节缓冲流BufferedInputStreamBufferedOutputStream
  • 字符缓冲流BufferedReaderBufferedWriter

缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。

字节缓冲流

字节缓冲流的构造方法

  • public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。
  • public BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流。

示例代码:

// 创建字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
// 创建字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));

拷贝文件效率测试

查询API,缓冲流读写方法与基本的流是一致的,通过复制大文件(375MB),测试它的效率。

  1. 基本流,代码如下:
public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 记录开始时间
      	long start = System.currentTimeMillis();
		// 创建流对象
        try (
        	FileInputStream fis = new FileInputStream("jdk8.exe");
        	FileOutputStream fos = new FileOutputStream("copy.exe")
        ){
        	// 读写数据
            int b;
            while ((b = fis.read()) != -1) {
                fos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// 记录结束时间
        long end = System.currentTimeMillis();
        System.out.println("普通流复制时间:"+(end - start)+" 毫秒");
    }
}
十几分钟过去了...
  1. 缓冲流,代码如下:
public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // 记录开始时间
      	long start = System.currentTimeMillis();
		// 创建流对象
        try (
        	BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk8.exe"));
	     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
        // 读写数据
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// 记录结束时间
        long end = System.currentTimeMillis();
        System.out.println("缓冲流复制时间:"+(end - start)+" 毫秒");
    }
}
缓冲流复制时间:8016 毫秒

如何更快呢?

使用数组的方式,代码如下:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
      	// 记录开始时间
        long start = System.currentTimeMillis();
		// 创建流对象
        try (
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk8.exe"));
		 BufferedOutputStream 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();
        }
		// 记录结束时间
        long end = System.currentTimeMillis();
        System.out.println("缓冲流使用数组复制时间:"+(end - start)+" 毫秒");
    }
}
缓冲流使用数组复制时间:666 毫秒

字符缓冲流

字符缓冲流的构造方法

  • public BufferedReader(Reader in) :创建一个 新的缓冲输入流。
  • public BufferedWriter(Writer out): 创建一个新的缓冲输出流。

构造举例,代码如下:

// 创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// 创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

字符缓冲流的特有方法

字符缓冲流的基本方法与普通字符流调用方式一致,来看它们具备的特有方法。

  • BufferedReader:public String readLine(): 读一行文字。
  • BufferedWriter:public void newLine(): 写一行行分隔符,由系统属性定义符号。

readLine方法演示,代码如下:

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
      	 // 创建流对象
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
		// 定义字符串,保存读取的一行文字
        String line  = null;
      	// 循环读取,读取到最后返回null
        while ((line = br.readLine())!=null) {
            System.out.print(line);
            System.out.println("------");
        }
		// 释放资源
        br.close();
    }
}

newLine方法演示,代码如下:

public class BufferedWriterDemo throws IOException {
  public static void main(String[] args) throws IOException  {
    	// 创建流对象
  	BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
    	// 写出数据
      bw.write("XX");
    	// 写出换行
      bw.newLine();
      bw.write("XX");
      bw.newLine();
      bw.write("X");
      bw.newLine();
  	// 释放资源
      bw.close();
  }
}
输出效果:
XX
XX
X

文本排序

  1. 逐行读取文本信息。
  2. 解析文本信息到集合中。
  3. 遍历集合,按顺序,写出文本信息。
  • 实现
public class Test {
    public static void main(String[] args) throws Exception {
        // 1.创建一个ArrayList集合,用来存储读取到的每行数据
        ArrayList<String> list = new ArrayList<>();
        // 2.创建字符缓冲输入流对象
        FileReader fr = new FileReader("a\\aaa\\c.txt");
        BufferedReader br = new BufferedReader(fr);

        // 3.定义一个String类型的变量,用来存储读取到的行数据
        String line;
        // 4.循环读取
        while ((line = br.readLine()) != null) {
            // 5.在循环中,把读取到的行数据作为元素添加到集合中
            list.add(line);
        }
        // 6.关闭流,释放资源
        fr.close();

        // 7.对集合进行排序
        Collections.sort(list); // 字符串的升序排序,String类型实现Comparable  compareTo方法: 指定的就是按照字典排序
        //  b  a  c   ---> 字典顺序   a  b  c

        // 8.创建字符缓冲输出流对象
        FileWriter fw = new FileWriter("a\\aaa\\c.txt");// 清空文件
        BufferedWriter bw = new BufferedWriter(fw);

        // 9.对排行序的集合进行循环遍历
        for (String s : list) {
            // 10.在循环中,把遍历出来的行数据写出到c.txt文件中
            bw.write(s);
            bw.newLine();
        }
        // 11.关闭流,释放资源
        bw.close();
    }
}

转换流

字符编码和字符集

字符编码的概述

计算机中储存的信息都是用二进制数表示的,而在屏幕上看到的数字、英文、标点符号、汉字等字符是二进制数转换之后的结果。按照某种规则,将字符存储到计算机中,称为编码 。反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为解码 。比如说,按照A规则存储,同样按照A规则解析,那么就能显示正确的文本f符号。反之,按照A规则存储,再按照B规则解析,就会导致乱码现象。

  • 字符编码Character Encoding : 就是一套自然语言的字符与二进制数之间的对应规则。

字符集的概述

  • 字符集 Charset:也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。

计算机要准确的存储和识别各种字符集符号,需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBK字符集、Unicode字符集等。
在这里插入图片描述
可见,当指定了编码,它所对应的字符集自然就指定了,所以编码才是最终要关心的

  • ASCII字符集
    • ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统,用于显示现代英语,主要包括控制字符(回车键、退格、换行键等)和可显示字符(英文大小写字符、阿拉伯数字和西文符号)。
    • 基本的ASCII字符集,使用7位(bits)表示一个字符,共128字符。ASCII的扩展字符集使用8位(bits)表示一个字符,共256字符,方便支持欧洲常用字符
  • ISO-8859-1字符集
    • 拉丁码表,别名Latin-1,用于显示欧洲使用的语言,包括荷兰、丹麦、德语、意大利语、西班牙语等。
    • ISO-5559-1使用单字节编码,兼容ASCII编码。
  • GBxxx字符集
    • GB就是国标的意思,是为了显示中文而设计的一套字符集。
    • GB2312:简体中文码表。一个小于127的字符的意义与原来相同。但两个大于127的字符连在一起时,就表示一个汉字,这样大约可以组合了包含7000多个简体汉字,此外数学符号、罗马希腊的字母、日文的假名们都编进去了,连在ASCII里本来就有的数字、标点、字母都统统重新编了两个字节长的编码,这就是常说的"全角"字符,而原来在127号以下的那些就叫"半角"字符了。
    • GBK:最常用的中文码表。是在GB2312标准基础上的扩展规范,使用了双字节编码方案,共收录了21003个汉字,完全兼容GB2312标准,同时支持繁体汉字以及日韩汉字等。
    • GB18030:最新的中文码表。收录汉字70244个,采用多字节编码,每个字可以由1个、2个或4个字节组成。支持中国国内少数民族的文字,同时支持繁体汉字以及日韩汉字等。
  • Unicode字符集
    • Unicode编码系统为表达任意语言的任意字符而设计,是业界的一种标准,也称为统一码、标准万国码。
    • 它最多使用4个字节的数字来表达每个字母、符号,或者文字。有三种编码方案,UTF-8、UTF-16和UTF-32。最为常用的UTF-8编码。
    • UTF-8编码,可以用来表示Unicode标准中任何字符,它是电子邮件、网页及其他存储或传送文字的应用中,优先采用的编码。互联网工程工作小组(IETF)要求所有互联网协议都必须支持UTF-8编码。所以,开发Web应用,也要使用UTF-8编码。它使用一至四个字节为每个字符编码,编码规则:
      1. 128个US-ASCII字符,只需一个字节编码。
      2. 拉丁文等字符,需要二个字节编码。
      3. 大部分常用字(含中文),使用三个字节编码。
      4. 其他极少使用的Unicode辅助字符,使用四字节编码。

编码引出的问题

在IDEA中,使用FileReader 读取项目中的文本文件。由于IDEA的设置,都是默认的UTF-8编码,所以没有任何问题。但是,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。

public class ReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("E:\\File_GBK.txt");
        int read;
        while ((read = fileReader.read()) != -1) {
            System.out.print((char)read);
        }
        fileReader.close();
    }
}
输出结果:
���

InputStreamReader类

InputStreamReader类的概述

转换流java.io.InputStreamReader,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。

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");

InputStreamReader类指定编码读取

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));
      	// 创建流对象,指定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类的概述

转换流java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。

OutputStreamWriter类的构造方法

  • OutputStreamWriter(OutputStream in): 创建一个使用默认字符集的字符流。 idea默认的是utf8
  • OutputStreamWriter(OutputStream in, String charsetName): 创建一个指定字符集的字符流。

构造举例,代码如下:

OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");

OutputStreamWriter类指定编码读取

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编码的文本文件,转换为UTF-8编码的文本文件。
  • 分析
    1.指定GBK编码的转换流,读取文本文件。
    2.使用UTF-8编码的转换流,写出文本文件。
  • 实现
public class TransDemo {
   public static void main(String[] args) {      
    	// 1.定义文件路径
     	String srcFile = "file_gbk.txt";
        String destFile = "file_utf8.txt";
		// 2.创建流对象
    	// 2.1 转换输入流,指定GBK编码
        Reader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");
    	// 2.2 转换输出流,默认utf8编码
        Writer 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();
  	}
}

序列化

序列化和反序列化的概念

Java 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该对象的数据对象的类型对象中存储的属性等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化对象的数据对象的类型对象中存储的数据信息,都可以用来在内存中创建对象。看图理解序列化:
在这里插入图片描述

ObjectOutputStream类

ObjectOutputStream类的概述

java.io.ObjectOutputStream 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。

ObjectOutputStream类构造方法

  • public ObjectOutputStream(OutputStream out): 创建一个指定OutputStream的ObjectOutputStream。

构造举例,代码如下:

FileOutputStream fileOut = new FileOutputStream("employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);

ObjectOutputStream类序列化操作

  1. 一个对象要想序列化,必须满足两个条件:
  • 该类必须实现java.io.Serializable 接口,Serializable 是一个标记接口
  • 该类的所有属性必须是可序列化的。
public class Person implements Serializable {
    private String name;
    private int age;

    public Animal anl;// 宠物

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

   //...set get ...toString...
}

public class Animal implements Serializable {
}

2.写出对象方法

  • public final void writeObject (Object obj) : 将指定的对象写出。
public class Test {
    public static void main(String[] args) throws Exception{
        // 使用ObjectOutputStream类序列化一个Person对象到文件中
        // 创建Person对象
        Person p = new Person("小明",18);
        Animal anl = new Animal();
        p.anl = anl;

        // 创建序列化流对象,关联目的地文件路径
        FileOutputStream fos = new FileOutputStream("a\\ccc\\a.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        // 写出对象
        oos.writeObject(p);
        // 关闭流,释放资源
        oos.close();
    }
}

ObjectInputStream类

ObjectInputStream类的概述

ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。

ObjectInputStream类构造方法

public ObjectInputStream(InputStream in): 创建一个指定InputStream的ObjectInputStream。

ObjectInputStream类反序列化操作1

如果能找到一个对象的class文件,可以进行反序列化操作,调用ObjectInputStream读取对象的方法:

  • public final Object readObject () : 读取一个对象。
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);	// zhangsan
        System.out.println("Address: " + e.address); // beiqinglu
        System.out.println("age: " + e.age); // 0
    }
}

序列化和反序列化注意事项

序列化的注意事项

  • 该类必须实现java.io.Serializable 接口,Serializable 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出NotSerializableException
  • 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用transient 关键字修饰。

反序列化的注意事项

  • 对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个 ClassNotFoundException 异常。

  • 另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个InvalidClassException异常。发生这个异常的原因如下:

    • 该类的序列版本号与从流中读取的类描述符的版本号不匹配
    • 该类包含未知数据类型
    • 该类没有可访问的无参数构造方法

Serializable 接口给需要序列化的类,提供了一个序列版本号。serialVersionUID 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。

public class Employee implements java.io.Serializable {
     // 加入序列版本号
     private static final long serialVersionUID = 1L;
     public String name;
     public String address;
     // 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
     public int eid; 

     public void addressCheck() {
         System.out.println("Address  check : " + name + " -- " + address);
     }
}

序列化集合

  • 需求
  1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。
  2. 反序列化list.txt ,并遍历集合,打印对象信息。
  • 分析
  1. 把若干学生对象 ,保存到集合中。
  2. 把集合序列化。
  3. 反序列化读取时,只需要读取一次,转换为集合类型。
  4. 遍历集合,可以打印所有的学生信息
  • 实现
public class SerTest {
	public static void main(String[] args) throws Exception {
		// 创建 学生对象
		Student student = new Student("小明", "xiaoming");
		Student student2 = new Student("小红", "xiaohong");
		Student student3 = new Student("小爱", "xiaoai");

		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();
	}
}

打印流

打印流的概述

平时在控制台打印输出,是调用print方法和println方法完成的,这两个方法都来自于java.io.PrintStream类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式。

打印流的使用

  • public PrintStream(String fileName): 使用指定的文件名创建一个新的打印流。

构造举例,代码如下:

PrintStream ps = new PrintStream("ps.txt")

System.out就是PrintStream类型的,只不过它的流向是系统规定的,打印在控制台上。不过,既然是流对象,我们就可以玩一个"小把戏",将数据输出到指定文本文件中。

public class Test {
    public static void main(String[] args) throws Exception {       
        // 指定路径打印
        /*// 创建打印流对象
        PrintStream ps = new PrintStream("a\\ddd\\a.txt");

        // 打印数据
        ps.println(100);
        ps.println("java");
        ps.println(true);

        // 关闭流,释放资源
        ps.close();*/

        // 系统的打印是默认打印到控制台
        System.out.println("java1");

        PrintStream ps = System.out;
        ps.println("java2");

        // 改变系统打印流打印数据的目的地
        PrintStream ps2 = new PrintStream("a\\ddd\\b.txt");
        // 设置系统类的打印流对象为ps2
        System.setOut(ps2);
        System.out.println("java3");// 打印b.txt文件中
    }
}

装饰设计模式

装饰模式概述

在缓冲流中涉及到java的一种设计模式,叫做装饰模式,来看下这个设计模式。
装饰模式指的是在不改变原类, 不使用继承的基础上,动态地扩展一个对象的功能。

装饰模式遵循原则:

  1. 装饰类和被装饰类必须实现相同的接口
  2. 在装饰类中必须传入被装饰类的引用
  3. 在装饰类中对需要扩展的方法进行扩展
  4. 在装饰类中对不需要扩展的方法调用被装饰类中的同名方法

示例代码

  • 准备环境:
  1. 编写一个Star接口, 提供sing 和 dance抽象方法
  2. 编写一个LiuDeHua类,实现Star接口,重写抽象方法
public interface Star {
    public void sing();
    public void dance();
}
public class XiaoMing implements Star {
    @Override
    public void sing() {
        System.out.println("小明在唱歌...");
    }
    @Override
    public void dance() {
        System.out.println("小明在跳舞...");
    }
}
  • 需求:

​ 在不改变原类的基础上对XiaoMing类的sing方法进行扩展

  • 实现步骤:
    1.编写一个XiaoMingWarpper类, 实现Star接口,重写抽象方法
    2.提供XiaoMingWarpper类的有参构造, 传入XiaoMing类对象
    3.在XiaoMingWarpper类中对需要增强的sing方法进行增强
    4.在XiaoMingWarpper类对不需要增强的方法调用XiaoMing类中的同名方法
  • 实现代码如下

XiaoMing类: 被装饰类

XiaoMingWarpper类: 我们称之为装饰类

/*
	装饰模式遵循原则:
		装饰类和被装饰类必须实现相同的接口
		在装饰类中必须传入被装饰类的引用
		在装饰类中对需要扩展的方法进行扩展
		在装饰类中对不需要扩展的方法调用被装饰类中的同名方法
*/
public class XiaoMingaWarpper implements Star {
    // 存放被装饰类的引用
    private XiaoMing xiaoMing;
    // 通过构造器传入被装饰类对象
    public XiaoMingWarpper(XiaoMing xiaoMing){
        this.xiaoMing = xiaoMing;
    }
    @Override
    public void sing() {
        // 对需要扩展的方法进行扩展增强
        System.out.println("小明在学校的舞台上演唱一路向北");
    }
    @Override
    public void dance() {
        // 不需要增强的方法调用被装饰类中的同名方法
        xiaoMing.dance();
    }
}
  • 测试结果
public static void main(String[] args) {
    // 创建被装饰类对象
    XiaoMing xiaoMing = new XiaoMing();
    // 创建装饰类对象,被传入被装饰类
    XiaoMingWarpper xiaoMingWarpper = new XiaoMingWarpper(xiaoMing);
    // 调用装饰类的相关方法,完成方法扩展
    xiaoMingWarpper.sing();
    xiaoMingWarpper.dance();
}

commons-io工具包

commons-io工具包的概述

commons-io是apache开源基金组织提供的一组有关IO操作的类库,可以挺提高IO功能开发的效率。commons-io工具包提供了很多有关io操作的类,见下表:

功能描述
org.apache.commons.io有关Streams、Readers、Writers、Files的工具类
org.apache.commons.io.input输入流相关的实现类,包含Reader和InputStream
org.apache.commons.io.output输出流相关的实现类,包含Writer和OutputStream
org.apache.commons.io.serialization序列化相关的类

commons-io工具包的步骤

步骤:

  1. 下载commons-io相关jar包;http://commons.apache.org/proper/commons-io/
  2. 把commons-io-2.6.jar包复制到指定的Module的lib目录中
  3. 将commons-io-2.6.jar加入到classpath中

commons-io工具包的使用

  • commons-io提供了一个工具类 org.apache.commons.io.IOUtils,封装了大量IO读写操作的代码。其中有两个常用方法:
  1. public static int copy(InputStream in, OutputStream out); 把input输入流中的内容拷贝到output输出流中,返回拷贝的字节个数(适合文件大小为2GB以下)
  2. public static long copyLarge(InputStream in, OutputStream out);把input输入流中的内容拷贝到output输出流中,返回拷贝的字节个数(适合文件大小为2GB以上)

文件复制案例演示:

 // IOUtils工具类拷贝文件
    private static void method01() throws IOException {
        FileInputStream fis = new FileInputStream("a\\aaa\\jdk11.exe");
        FileOutputStream fos = new FileOutputStream("a\\aaa\\jdk11Copy4.exe");
        IOUtils.copy(fis,fos);
        fos.close();
        fis.close();
    }
  • commons-io还提供了一个工具类org.apache.commons.io.FileUtils,封装了一些对文件操作的方法:
  1. public static void copyFileToDirectory(final File srcFile, final File destFile) //复制文件到另外一个目录下。
  2. public static void copyDirectoryToDirectory( file1 , file2 );//复制file1目录到file2位置。

案例演示:

public static void main(String[] args) throws IOException {
		// FileUtils工具类拷贝文件到指定文件夹
        // File srcFile = new File("a\\aaa\\a.txt");
        // File destFile = new File("a\\eee");
        // FileUtils.copyFileToDirectory(srcFile,destFile);

        // FileUtils工具类拷贝文件夹到指定文件夹
        File srcFile = new File("a\\ddd");
        File destFile = new File("a\\eee");
   	    FileUtils.copyDirectoryToDirectory(srcFile,destFile);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值