• Java基础-IO流


    目录

    1 File 类的使用

    1.1 File类的概念

    1.2 构造方法

    1.3 常用方法

    1.4 课后练习

    2 IO流原理及流的分类

    2.1 IO原理

    2.2 流的分类

    2.3 IO流体系

    2.4 接口方法

    2.4.1 InputStream & Reader相同点

    2.4.2 InputStream方法详解

    2.4.3 Reader方法详解

    2.4.4 OutputStream & Writer相同点

    2.4.5 OutputStream方法详解

    2.4.6 Writer方法详解

    3 节点流(或文件流)

    3.1 读取文件通用步骤

    3.2 FileReader read(char[] cbuf)方法读取文件

    3.3 写出数据通用步骤

    3.4 FileReader和FileWriter实现文本文件复制(不能实现非文本文件复制)

    3.5 FileInputStream不能读取文本文件(复制操作可以)

    3.6 FileInputStream和FileOutputStream读写非文本文件

    3.7 FileInputStream和FileOutputStream复制文件

    3.8 输入流重复使用

    4 缓冲流

    4.1 基本概念

    4.2 原理图

    4.3 缓冲流(字节型)实现非文本文件的复制

    4.4 缓冲流与节点流读写速度对比

    4.5 缓冲流(字符型)实现文本文件的复制

    4.6 缓冲流课后练习

    5 转换流

    5.1 概述

    5.2 原理图

    5.3 转换流读取文件

    5.4 转换流实现文件的读入和写出

    5.5 字符编码

    6 标准输入、输出流

    7 打印流

    8 数据流

    9 对象流

    9.1 对象序列化概念

    9.2 对象流序列化与反序列化字符串操作

    9.3 自定义类实现序列化与反序列化操作

    9.3 serialVersionUID的理解

    9.4 自定义类可序列化的其他要求

    10 随机存取文件流

    10.1 RandomAccessFile实现数据的读写操作

    10.2 RandomAccessFile实现数据的插入

    10.3 扩展

    11 NIO.2中Path、Paths、Files类的使用

    11.1 概述

    10.2 Path接口

    10.3 Files 类

    10.4  FileUtils


    1 File 类的使用

    1.1 File类的概念

    • java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关
    • File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。 如果需要访问文件内容本身,则需要使用输入/输出流。
    • 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对 象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
    • File对象可以作为参数传递给流的构造器

    1.2 构造方法

    1. /**
    2. * 1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
    3. * 2. File类声明在java.io包下
    4. * 3. File类中涉及到关于文件或文件目录的创建/删除重命名/修改时间、文件大小等方法.并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容.必须使用IO流来完成。
    5. * 4. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点"。
    6. *
    7. */
    8. public class FileTest {
    9. /*
    10. 1.如何创建File类的实例
    11. 1.1 File(String filePath)
    12. 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果 pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
    13.  绝对路径:是一个固定的路径,从盘符开始
    14.  相对路径:是相对于某个位置开始
    15. 1.2 File(String parentPath,String childPath)
    16. 以parent为父路径,child为子路径创建File对象。
    17. 1.3 File(File parentFile,String childPath)
    18. 根据一个父File对象和子文件路径创建File对象
    19. 2.
    20. 相对路径:相较于某个路径下,指明的路径。
    21. 绝对路径:包含盘符在内的文件或文件目录的路径
    22. 3.路径分隔符
    23. windows:\\
    24. unix:/
    25. */
    26. @Test
    27. public void test01(){
    28. //构造器1
    29. File file1 = new File("hello1.txt");//相对于整个工程(即javaSE)
    30. File file2 = new File("hello.txt");//相对于整个工程(即javaSE)
    31. File file3 = new File("/data/test/hello.txt");
    32. System.out.println("file1: "+file1 +" ============ file1 exists: "+file1.exists());
    33. System.out.println("file2: "+file2 +" ============ file2 exists: "+file2.exists());
    34. System.out.println("file3: "+file3 +" ============ file3 exists: "+file3.exists());
    35. //构造器2:
    36. File file4 = new File("/data", "test");
    37. System.out.println("file4: "+file4 +" ============ file4 exists: "+file4.exists());
    38. //构造器3:
    39. File file5 = new File(file4, "hello.txt");
    40. System.out.println("file5: "+file5 +" ============ file5 exists: "+file5.exists());
    41. }
    42. }
    43. --输出
    44. file1: hello1.txt ============ file1 exists: false
    45. file2: hello.txt ============ file2 exists: true
    46. file3: /data/test/hello.txt ============ file3 exists: true
    47. file4: /data/test ============ file4 exists: true
    48. file5: /data/test/hello.txt ============ file5 exists: true

    注意:图中hello.txt文件在javaSE下,与io文件夹同级别,可以看到hello.text在工程目录下能检索到,而hello1.txt在io模块下是检索不到的。

    1.3 常用方法

    • 获取文件路径/名称/大小

    1. /*
    2. public String getAbsolutePath():获取绝对路径
    3. public String getPath() :获取路径
    4. public String getName() :获取名称
    5. public String getParent():获取上层文件目录路径。若无,返回null
    6. public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
    7. public long lastModified() :获取最后一次的修改时间,毫秒值
    8. 如下的两个方法适用于文件目录:
    9. public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
    10. public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
    11. */
    12. @Test
    13. public void test2(){
    14. File file1 = new File("hello.txt");
    15. File file2 = new File("/data/test/hello.txt");
    16. System.out.println("绝对路径: "+file1.getAbsolutePath());
    17. System.out.println("相对路径: "+file1.getPath());
    18. System.out.println("文件名: "+file1.getName());
    19. System.out.println("上层文件目录路径: "+file1.getParent());
    20. System.out.println("文件大小: "+file1.length());
    21. System.out.println("修改时间: "+new Date(file1.lastModified()));
    22. System.out.println();
    23. System.out.println("绝对路径: "+file2.getAbsolutePath());
    24. System.out.println("相对路径: "+file2.getPath());
    25. System.out.println("文件名: "+file2.getName());
    26. System.out.println("上层文件目录路径: "+file2.getParent());
    27. System.out.println("文件大小: "+file2.length());
    28. System.out.println("修改时间: "+new Date(file2.lastModified()));
    29. }
    30. -- 输出:
    31. 绝对路径: /Users/lizhijian/IdeaProjects/study/javaSE/hello.txt
    32. 相对路径: hello.txt
    33. 文件名: hello.txt
    34. 上层文件目录路径: null
    35. 文件大小: 5
    36. 修改时间: Sun May 08 16:41:49 CST 2022
    37. 绝对路径: /data/test/hello.txt
    38. 相对路径: /data/test/hello.txt
    39. 文件名: hello.txt
    40. 上层文件目录路径: /data/test
    41. 文件大小: 5
    42. 修改时间: Sun May 08 16:41:49 CST 2022

    ps: 这里之所以为null,是因为getParent() 是根据创建File对象时输入的路径字符串解析的。因为file1对象是根据相对路径创建的,故 getParent()为null。

    参见源码:

    1. public String getParent() {
    2. int index = path.lastIndexOf(separatorChar);
    3. if (index < prefixLength) {
    4. if ((prefixLength > 0) && (path.length() > prefixLength))
    5. return path.substring(0, prefixLength);
    6. return null;
    7. }
    8. return path.substring(0, index);
    9. }
    • 遍历文件夹
    1. @Test
    2. public void test3(){
    3. File file = new File("/data/test");
    4. // 只能获取当前目录下的文件/文件夹无法递归获取
    5. String[] list = file.list();
    6. for(String s : list){
    7. System.out.println(s);
    8. }
    9. System.out.println();
    10. File[] files = file.listFiles();
    11. for(File f : files){
    12. System.out.println(f);
    13. }
    14. }
    15. --输出:
    16. .DS_Store
    17. hello.txt
    18. child
    19. /data/test/.DS_Store
    20. /data/test/hello.txt
    21. /data/test/child

    • 重命名
    1. /*
    2. public boolean renameTo(File dest):把文件重命名为指定的文件路径(重命名或移动文件)
    3. 比如:file1.renameTo(file2)为例:
    4. 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
    5. */
    6. @Test
    7. public void test4(){
    8. File file1 = new File("hello2.txt");
    9. File file2 = new File("/data/test/hello3.txt");
    10. boolean renameTo = file1.renameTo(file2);
    11. System.out.println(renameTo);
    12. }
    13. --输出:
    14. true
    • 判断功能
    1. /*
    2. public boolean isDirectory():判断是否是文件目录
    3. public boolean isFile() :判断是否是文件
    4. public boolean exists() :判断是否存在
    5. public boolean canRead() :判断是否可读
    6. public boolean canWrite() :判断是否可写
    7. public boolean isHidden() :判断是否隐藏
    8. */
    9. @Test
    10. public void test5(){
    11. File file1 = new File("hello.txt");
    12. System.out.println("是否是文件夹: "+file1.isDirectory());
    13. System.out.println("是否是文件: " + file1.isFile());
    14. System.out.println("是否存在: " + file1.exists());
    15. System.out.println("是否可读: " +file1.canRead());
    16. System.out.println("是否可写: " +file1.canWrite());
    17. System.out.println("是否隐藏: " +file1.isHidden());
    18. System.out.println();
    19. File file2 = new File("/data/test");
    20. System.out.println("是否文件夹: "+file2.isDirectory());
    21. System.out.println("是否文件: " + file2.isFile());
    22. System.out.println("是否存在: " + file2.exists());
    23. System.out.println("是否可读: " +file2.canRead());
    24. System.out.println("是否可写: " +file2.canWrite());
    25. System.out.println("是否隐藏: " +file2.isHidden());
    26. }
    27. --输出:
    28. 是否是文件夹: false
    29. 是否是文件: true
    30. 是否存在: true
    31. 是否可读: true
    32. 是否可写: true
    33. 是否隐藏: false
    34. 是否文件夹: true
    35. 是否文件: false
    36. 是否存在: true
    37. 是否可读: true
    38. 是否可写: true
    39. 是否隐藏: false
    • 创建功能
    1. /*
    2. 创建硬盘中对应的文件或文件目录
    3. public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
    4. public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
    5. public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建
    6. */
    7. @Test
    8. public void test6() throws IOException {
    9. File file1 = new File("hello.txt");
    10. if(!file1.exists()){
    11. //文件的创建
    12. file1.createNewFile();
    13. System.out.println("创建成功");
    14. }else{//文件存在
    15. file1.delete();
    16. System.out.println("删除成功");
    17. }
    18. // 不能越级创建文件,至少保证上层文件夹存在才能创建,否则会报:java.io.IOException: No such file or directory
    19. File file2 = new File("/data/test/child3/child33/hello.txt");
    20. if(!file2.exists()){
    21. //文件的创建
    22. file2.createNewFile();
    23. System.out.println("创建成功");
    24. }else{//文件存在
    25. file2.delete();
    26. System.out.println("删除成功");
    27. }
    28. }
    29. @Test
    30. public void test7(){
    31. //文件目录的创建
    32. File file1 = new File("/data/test/child1/child11");
    33. // 单级创建
    34. boolean mkdir = file1.mkdir();
    35. if(mkdir){
    36. System.out.println("创建成功1");
    37. }
    38. File file2 = new File("/data/test/child1/child11");
    39. // 多级创建
    40. boolean mkdir1 = file2.mkdirs();
    41. if(mkdir1){
    42. System.out.println("创建成功2");
    43. }
    44. }
    • 删除功能 (找不到文件不抛异常)
    1. /**
    2. * 删除磁盘中的文件或文件目录
    3. * public boolean delete():删除文件或者文件夹
    4. * 删除注意事项:Java中的删除不走回收站。
    5. */
    6. @Test
    7. public void test8(){
    8. //要想删除成功,文件目录下不能有子目录或文件
    9. File file3 = new File("/data/test/child2");
    10. System.out.println(file3.delete());
    11. }
    12. --输出:
    13. false

    • 获取文件属性规则

    1.4 课后练习

    练习1 

    1. public class FileDemo {
    2. @Test
    3. public void test1() throws IOException {
    4. File parent = new File("/data/test");
    5. File file1 = new File(parent, "123");
    6. File file2 = new File(parent, "111.txt");
    7. file1.mkdir();
    8. file2.createNewFile();
    9. File delete1 = new File("/data/test","111.txt");
    10. File delete2 = new File("/data/test","123");
    11. delete1.delete();
    12. delete2.delete();
    13. }
    14. }

    练习2 

    1. @Test
    2. public void test1(){
    3. File srcFile = new File("d:\\code");
    4. String[] fileNames = srcFile.list();
    5. for(String fileName : fileNames){
    6. if(fileName.endsWith(".jpg")){
    7. System.out.println(fileName);
    8. }
    9. }
    10. }

    练习3

    1. public class ListFilesTest {
    2. public static void main(String[] args) {
    3. // 递归:文件目录
    4. /** 打印出指定目录所有文件名称,包括子文件目录中的文件 */
    5. // 1.创建目录对象
    6. File dir = new File("E:\\teach\\01_javaSE\\3");
    7. // 2.打印目录的子文件
    8. printSubFile(dir);
    9. }
    10. public static void printSubFile(File dir) {
    11. // 打印目录的子文件
    12. File[] subfiles = dir.listFiles();
    13. for (File f : subfiles) {
    14. if (f.isDirectory()) {// 文件目录
    15. printSubFile(f);
    16. } else {// 文件
    17. System.out.println(f.getAbsolutePath());
    18. }
    19. }
    20. }
    21. }

    2 IO流原理及流的分类

    2.1 IO原理

    • I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
    • Java程序中,对于数据的输入/输出操作以“流(stream)” 的 方式进行。
    •  java.io包下提供了各种“流”类和接口,用以获取不同种类的 数据,并通过标准的方法输入或输出数据。
    • 输入input:读取外部数据(磁 盘、光盘等存储设备的数据)到 程序(内存)中。
    • 输出output:将程序(内存) 数据输出到磁盘、光盘等存储设 备中。

    2.2 流的分类

    • 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit) 
    • 按数据流的流向不同分为:输入流,输出流
    • 按流的角色的不同分为:节点流,处理流

    • Java的IO流共涉及40多个类,实际上非常规则,都是从上面4个抽象基类派生的。
    • 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀

    2.3 IO流体系

    2.4 接口方法

    2.4.1 InputStream & Reader相同点

    • InputStream 和 Reader 是所有输入流的基类。
    • InputStream(典型实现:FileInputStream)
    • int read()
    • int read(byte[] b)
    • int read(byte[] b, int off, int len)
    • Reader(典型实现:FileReader)
    • int read()
    • int read(char [] c)
    • int read(char [] c, int off, int len)
    • 程序中打开的文件 IO 资源不属于内存里的资源,垃圾回收机制无法回收该资 源,所以应该显式关闭文件 IO 资源。
    • FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream 用于读取非文本数据之类的原始字节流。要读取字符流,需要使用 FileReader

    2.4.2 InputStream方法详解

    • int read()    从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因 为已经到达流末尾而没有可用的字节,则返回值 -1。
    • int read(byte[] b)      从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已 经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取 的字节数。
    • int read(byte[] b, int off,int len)    将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于 文件末尾而没有可用的字节,则返回值 -1。
    • public void close() throws IOException     关闭此输入流并释放与该流关联的所有系统资源。

    2.4.3 Reader方法详解

    • int read()    读取单个字符。作为整数读取的字符,范围在 0 到 65535 之间 (0x00-0xffff)(2个 字节的Unicode码),如果已到达流的末尾,则返回 -1
    • int read(char[] cbuf)    将字符读入数组。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数。
    •  int read(char[] cbuf,int off,int len)    将字符读入数组的某一部分。存到数组cbuf中,从off处开始存储,最多读len个字 符。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数。
    •  public void close() throws IOException     关闭此输入流并释放与该流关联的所有系统资源。

    2.4.4 OutputStream & Writer相同点

    • OutputStream 和 Writer 也非常相似方法如下:
      • void write(int b/int c);
      • void write(byte[] b/char[] cbuf);
      • void write(byte[] b/char[] buff, int off, int len);
      • void flush();
      • void close(); 需要先刷新,再关闭此流
    • 因为字符流直接以字符作为操作单位,所以 Writer 可以用字符串来替换字符数组, 即以 String 对象作为参数
      • void write(String str);
      • void write(String str, int off, int len);
    • FileOutputStream 从文件系统中的某个文件中获得输出字节。FileOutputStream用于写出非文本数据之类的原始字节流。要写出字符流,需要使用 FileWriter
    • 使用FileOutputStream时会自动创建文件,但是如果是多级目录,就创建不了并且报错。需要手动创建上级目录
    1. File f = new File(filePathAndName);
    2. if (!f.getParentFile().exists()) {
    3. f.getParentFile().mkdirs();
    4. }
    5. outputStream = new FileOutputStream(f);

    2.4.5 OutputStream方法详解

    • void write(int b)    将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写 入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 即写入0~255范围的。
    • void write(byte[] b)    将 b.length 个字节从指定的 byte 数组写入此输出流。write(b) 的常规协定是:应该 与调用 write(b, 0, b.length) 的效果完全相同。
    •  void write(byte[] b,int off,int len)    将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
    • public void flush()throws IOException     刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立即写入它们预期的目标。
    • public void close() throws IOException     关闭此输出流并释放与该流关联的所有系统资源。

    2.4.6 Writer方法详解

    • void write(int c)    写入单个字符。要写入的字符包含在给定整数值的 16 个低位中,16 高位被忽略。 即 写入0 到 65535 之间的Unicode码。
    • void write(char[] cbuf)    写入字符数组。
    • void write(char[] cbuf,int off,int len) 写入字符数组的某一部分。从off开始,写入len个字符
    • void write(String str)    写入字符串。
    • void write(String str,int off,int len)    写入字符串的某一部分。
    • void flush()    刷新该流的缓冲,则立即将它们写入预期目标。
    • public void close() throws IOException 关闭此输出流并释放与该流关联的所有系统资源。

    3 节点流(或文件流)

    3.1 读取文件通用步骤

    1.建立一个流对象,将已存在的一个文件加载进流。
    FileReader fr = new FileReader(new File(“Test.txt”));

    2.创建一个临时存放数据的数组。

    char[] ch = new char[1024];

    3.调用流对象的读取方法将流中的数据读入到数组中。

    fr.read(ch);

    4. 关闭资源。 

    fr.close();

    FileReader read()方法读取文件

    1. /**
    2. *
    3. * 一、流的分类:
    4. * 1.操作数据单位:字节流、字符流
    5. * 2.数据的流向:输入流、输出流
    6. * 3.流的角色:节点流、处理流
    7. *
    8. * 二、流的体系结构
    9. * 抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
    10. * InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer))
    11. * OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush()
    12. * Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
    13. * Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush()
    14. *
    15. *
    16. */
    17. public class FileReaderWriterTest {
    18. public static void main(String[] args) {
    19. File file = new File("hello.txt");//相较于当前工程
    20. System.out.println(file.getAbsolutePath());
    21. File file1 = new File("day09\\hello.txt");
    22. System.out.println(file1.getAbsolutePath());
    23. }
    24. /*
    25. 将hello.txt文件内容读入程序中,并输出到控制台
    26. 说明点:
    27. 1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
    28. 2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
    29. 3. 读入的文件一定要存在,否则就会报FileNotFoundException。
    30. */
    31. @Test
    32. public void testFileReader(){
    33. FileReader fr = null;
    34. try {
    35. //1.实例化File类的对象,指明要操作的文件
    36. File file = new File("hello.txt");//相较于当前Module
    37. //2.提供具体的流
    38. fr = new FileReader(file);
    39. //3.数据的读入
    40. //read():返回读入的一个字符。如果达到文件末尾,返回-1
    41. //方式一:
    42. // int data = fr.read();
    43. // while(data != -1){
    44. // System.out.print((char)data);
    45. // data = fr.read();
    46. // }
    47. //方式二:语法上针对于方式一的修改
    48. int data;
    49. while((data = fr.read()) != -1){
    50. System.out.print((char)data);
    51. }
    52. } catch (IOException e) {
    53. e.printStackTrace();
    54. } finally {
    55. //4.流的关闭操作
    56. // try {
    57. // if(fr != null)
    58. // fr.close();
    59. // } catch (IOException e) {
    60. // e.printStackTrace();
    61. // }
    62. //或
    63. if(fr != null){
    64. try {
    65. fr.close();
    66. } catch (IOException e) {
    67. e.printStackTrace();
    68. }
    69. }
    70. }
    71. }
    72. }

    3.2 FileReader read(char[] cbuf)方法读取文件

    1. //对read()操作升级:使用read的重载方法
    2. @Test
    3. public void testFileReader1() {
    4. FileReader fr = null;
    5. try {
    6. //1.File类的实例化
    7. File file = new File("hello.txt");
    8. //2.FileReader流的实例化
    9. fr = new FileReader(file);
    10. //3.读入的操作
    11. //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
    12. char[] cbuf = new char[5];
    13. int len;
    14. while((len = fr.read(cbuf)) != -1){
    15. //方式一:
    16. //错误的写法
    17. // for(int i = 0;i < cbuf.length;i++){
    18. // System.out.print(cbuf[i]);
    19. // }
    20. //正确的写法
    21. // for(int i = 0;i < len;i++){
    22. // System.out.print(cbuf[i]);
    23. // }
    24. //方式二:
    25. //错误的写法,对应着方式一的错误的写法
    26. // String str = new String(cbuf);
    27. // System.out.print(str);
    28. //正确的写法
    29. String str = new String(cbuf,0,len);
    30. System.out.print(str);
    31. }
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. } finally {
    35. if(fr != null){
    36. //4.资源的关闭
    37. try {
    38. fr.close();
    39. } catch (IOException e) {
    40. e.printStackTrace();
    41. }
    42. }
    43. }
    44. }

    3.3 写出数据通用步骤

    1.创建流对象,建立数据存放文件
    FileWriter fw = new FileWriter(new File(“Test.txt”));

    2.调用流对象的写入方法,将数据写入流

    fw.write(“atguigu-songhongkang”);

    3.关闭流资源,并将流中的数据清空到文件中。

    fw.close();

    FileWriter写数据的操作

    1. /*
    2. 从内存中写出数据到硬盘的文件里。
    3. 说明:
    4. 1. 输出操作,对应的File可以不存在的。并不会报异常
    5. 2.
    6. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
    7. File对应的硬盘中的文件如果存在:
    8. 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
    9. 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
    10. 3. 在new FileWriter();时如果文件不存在,即会创建文件
    11. */
    12. @Test
    13. public void testFileWriter() {
    14. FileWriter fw = null;
    15. try {
    16. //1.提供File类的对象,指明写出到的文件
    17. File file = new File("hello1.txt");
    18. //2.提供FileWriter的对象,用于数据的写出
    19. fw = new FileWriter(file,false);
    20. //3.写出的操作
    21. fw.write("I have a dream!\n");
    22. fw.write("you need to have a dream!");
    23. } catch (IOException e) {
    24. e.printStackTrace();
    25. } finally {
    26. //4.流资源的关闭
    27. if(fw != null){
    28. try {
    29. fw.close();
    30. } catch (IOException e) {
    31. e.printStackTrace();
    32. }
    33. }
    34. }
    35. }

    3.4 FileReader和FileWriter实现文本文件复制(不能实现非文本文件复制)

    1. @Test
    2. public void testFileReaderFileWriter() {
    3. FileReader fr = null;
    4. FileWriter fw = null;
    5. try {
    6. //1.创建File类的对象,指明读入和写出的文件
    7. File srcFile = new File("hello.txt");
    8. File destFile = new File("hello2.txt");
    9. //不能使用字符流来处理图片等字节数据
    10. // File srcFile = new File("爱情与友情.jpg");
    11. // File destFile = new File("爱情与友情1.jpg");
    12. //2.创建输入流和输出流的对象
    13. fr = new FileReader(srcFile);
    14. fw = new FileWriter(destFile);
    15. //3.数据的读入和写出操作
    16. char[] cbuf = new char[5];
    17. int len;//记录每次读入到cbuf数组中的字符的个数
    18. while((len = fr.read(cbuf)) != -1){
    19. //每次写出len个字符
    20. fw.write(cbuf,0,len);
    21. }
    22. } catch (IOException e) {
    23. e.printStackTrace();
    24. } finally {
    25. //4.关闭流资源
    26. //方式一:
    27. // try {
    28. // if(fw != null)
    29. // fw.close();
    30. // } catch (IOException e) {
    31. // e.printStackTrace();
    32. // }finally{
    33. // try {
    34. // if(fr != null)
    35. // fr.close();
    36. // } catch (IOException e) {
    37. // e.printStackTrace();
    38. // }
    39. // }
    40. //方式二:
    41. try {
    42. if(fw != null)
    43. fw.close();
    44. } catch (IOException e) {
    45. e.printStackTrace();
    46. }
    47. try {
    48. if(fr != null)
    49. fr.close();
    50. } catch (IOException e) {
    51. e.printStackTrace();
    52. }
    53. }
    54. }

    3.5 FileInputStream不能读取文本文件(复制操作可以)

    1. //使用字节流FileInputStream处理文本文件,可能出现乱码。
    2. @Test
    3. public void testFileInputStream() {
    4. FileInputStream fis = null;
    5. try {
    6. //1. 造文件
    7. File file = new File("hello.txt");
    8. //2.造流
    9. fis = new FileInputStream(file);
    10. //3.读数据
    11. byte[] buffer = new byte[5];
    12. int len;//记录每次读取的字节的个数
    13. while((len = fis.read(buffer)) != -1){
    14. String str = new String(buffer,0,len);
    15. System.out.print(str);
    16. }
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. } finally {
    20. if(fis != null){
    21. //4.关闭资源
    22. try {
    23. fis.close();
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. }
    29. }

    错误输出:

    原因:UTF-8编码下,一个字母占一个字节,一个汉字占三个字节,复制的字节数组长度是5,恰好把“中”进行了切割,无法复制全,即“中”无法正常显示。

    3.6 FileInputStream和FileOutputStream读写非文本文件

    1. @Test
    2. public void testFileInputOutputStream() {
    3. FileInputStream fis = null;
    4. FileOutputStream fos = null;
    5. try {
    6. //
    7. File srcFile = new File("爱情与友情.jpg");
    8. File destFile = new File("爱情与友情2.jpg");
    9. //
    10. fis = new FileInputStream(srcFile);
    11. fos = new FileOutputStream(destFile);
    12. //复制的过程
    13. byte[] buffer = new byte[5];
    14. int len;
    15. while((len = fis.read(buffer)) != -1){
    16. fos.write(buffer,0,len);
    17. }
    18. } catch (IOException e) {
    19. e.printStackTrace();
    20. } finally {
    21. if(fos != null){
    22. //
    23. try {
    24. fos.close();
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. if(fis != null){
    30. try {
    31. fis.close();
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. }
    37. }

    3.7 FileInputStream和FileOutputStream复制文件

    1. //指定路径下文件的复制
    2. public void copyFile(String srcPath,String destPath){
    3. FileInputStream fis = null;
    4. FileOutputStream fos = null;
    5. try {
    6. //
    7. File srcFile = new File(srcPath);
    8. File destFile = new File(destPath);
    9. //
    10. fis = new FileInputStream(srcFile);
    11. fos = new FileOutputStream(destFile);
    12. //复制的过程
    13. byte[] buffer = new byte[1024];
    14. int len;
    15. while((len = fis.read(buffer)) != -1){
    16. fos.write(buffer,0,len);
    17. }
    18. } catch (IOException e) {
    19. e.printStackTrace();
    20. } finally {
    21. if(fos != null){
    22. //
    23. try {
    24. fos.close();
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. if(fis != null){
    30. try {
    31. fis.close();
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. }
    37. }
    38. @Test
    39. public void testCopyFile(){
    40. long start = System.currentTimeMillis();
    41. String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi";
    42. String destPath = "C:\\Users\\Administrator\\Desktop\\02-视频.avi";
    43. // String srcPath = "hello.txt";
    44. // String destPath = "hello3.txt";
    45. copyFile(srcPath,destPath);
    46. long end = System.currentTimeMillis();
    47. System.out.println("复制操作花费的时间为:" + (end - start));//618
    48. }

    3.8 输入流重复使用

    文件上传时可能会涉及输入流重复使用问题,但是输入流本身只能使用一次,可以用以下方式进行重复读取

    1. // 获取上传的文件
    2. MultipartFile fundFile = fileInfo.getFile();
    3. // 获取上传文件输入流
    4. inputStream = fundFile.getInputStream();
    5. // 输出流(模拟输出给文件)
    6. FileOutputStream outputStream = new FileOutputStream(new File("abc.txt"));
    7. // 定义buffer[]
    8. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()
    9. // 将输入流拷贝到buffer[] (经过copy后inputStream指针发生了偏移,不能再次使用)
    10. IOUtils.copy(inputStream,byteArrayOutputStream);
    11. // 将buffer[]写入到输出流(写给文件)
    12. byteArrayOutputStream.writeTo(outputStream);
    13. // 将buffer[]再次赋值给输入流,inputStream可以重新使用
    14. inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    15. // 再次使用inputStream 实例化excel对象
    16. Workbook wb = null;
    17. if (inputFilePath.toString().endsWith("xlsx")) {
    18. wb = new XSSFWorkbook(inputStream);
    19. } else {
    20. wb = new HSSFWorkbook(inputStream);
    21. }

    4 缓冲流

    4.1 基本概念

    • 为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。

    • 缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
      • BufferedInputStream  和 BufferedOutputStream
      • BufferedReader 和 BufferedWriter
    • 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区
    • 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从 文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中 读取下一个8192个字节数组。
    • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满, BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法 flush()可以强制将缓冲区的内容全部写入输出流
    • 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也 会相应关闭内层节点流
    • flush()方法的使用:手动将buffer中内容写入文件
    • 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷 新缓冲区,关闭后不能再写出

    4.2 原理图

    4.3 缓冲流(字节型)实现非文本文件的复制

    1. /**
    2. * 处理流之一:缓冲流的使用
    3. *
    4. * 1.缓冲流:
    5. * BufferedInputStream
    6. * BufferedOutputStream
    7. * BufferedReader
    8. * BufferedWriter
    9. *
    10. * 2.作用:提供流的读取、写入的速度
    11. * 提高读写速度的原因:内部提供了一个缓冲区
    12. *
    13. * 3. 处理流,就是“套接”在已有的流的基础上。
    14. *
    15. */
    16. public class BufferedTest {
    17. /*
    18. 实现非文本文件的复制
    19. */
    20. @Test
    21. public void BufferedStreamTest() throws FileNotFoundException {
    22. BufferedInputStream bis = null;
    23. BufferedOutputStream bos = null;
    24. try {
    25. //1.造文件
    26. File srcFile = new File("爱情与友情.jpg");
    27. File destFile = new File("爱情与友情3.jpg");
    28. //2.造流
    29. //2.1 造节点流
    30. FileInputStream fis = new FileInputStream((srcFile));
    31. FileOutputStream fos = new FileOutputStream(destFile);
    32. //2.2 造缓冲流
    33. bis = new BufferedInputStream(fis);
    34. bos = new BufferedOutputStream(fos);
    35. //3.复制的细节:读取、写入
    36. byte[] buffer = new byte[10];
    37. int len;
    38. while((len = bis.read(buffer)) != -1){
    39. bos.write(buffer,0,len);
    40. // bos.flush();//刷新缓冲区
    41. }
    42. } catch (IOException e) {
    43. e.printStackTrace();
    44. } finally {
    45. //4.资源关闭
    46. //要求:先关闭外层的流,再关闭内层的流
    47. if(bos != null){
    48. try {
    49. bos.close();
    50. } catch (IOException e) {
    51. e.printStackTrace();
    52. }
    53. }
    54. if(bis != null){
    55. try {
    56. bis.close();
    57. } catch (IOException e) {
    58. e.printStackTrace();
    59. }
    60. }
    61. //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
    62. // fos.close();
    63. // fis.close();
    64. }
    65. }
    66. }

    4.4 缓冲流与节点流读写速度对比

    1. //实现文件复制的方法
    2. public void copyFileWithBuffered(String srcPath,String destPath){
    3. BufferedInputStream bis = null;
    4. BufferedOutputStream bos = null;
    5. try {
    6. //1.造文件
    7. File srcFile = new File(srcPath);
    8. File destFile = new File(destPath);
    9. //2.造流
    10. //2.1 造节点流
    11. FileInputStream fis = new FileInputStream((srcFile));
    12. FileOutputStream fos = new FileOutputStream(destFile);
    13. //2.2 造缓冲流
    14. bis = new BufferedInputStream(fis);
    15. bos = new BufferedOutputStream(fos);
    16. //3.复制的细节:读取、写入
    17. byte[] buffer = new byte[1024];
    18. int len;
    19. while((len = bis.read(buffer)) != -1){
    20. bos.write(buffer,0,len);
    21. }
    22. } catch (IOException e) {
    23. e.printStackTrace();
    24. } finally {
    25. //4.资源关闭
    26. //要求:先关闭外层的流,再关闭内层的流
    27. if(bos != null){
    28. try {
    29. bos.close();
    30. } catch (IOException e) {
    31. e.printStackTrace();
    32. }
    33. }
    34. if(bis != null){
    35. try {
    36. bis.close();
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
    42. // fos.close();
    43. // fis.close();
    44. }
    45. }
    46. @Test
    47. public void testCopyFileWithBuffered(){
    48. long start = System.currentTimeMillis();
    49. String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi";
    50. String destPath = "C:\\Users\\Administrator\\Desktop\\03-视频.avi";
    51. copyFileWithBuffered(srcPath,destPath);
    52. long end = System.currentTimeMillis();
    53. System.out.println("复制操作花费的时间为:" + (end - start));//618 - 176
    54. }

    4.5 缓冲流(字符型)实现文本文件的复制

    1. /*
    2. 使用BufferedReader和BufferedWriter实现文本文件的复制
    3. */
    4. @Test
    5. public void testBufferedReaderBufferedWriter(){
    6. BufferedReader br = null;
    7. BufferedWriter bw = null;
    8. try {
    9. //创建文件和相应的流
    10. br = new BufferedReader(new FileReader(new File("dbcp.txt")));
    11. bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
    12. //读写操作
    13. //方式一:使用char[]数组
    14. // char[] cbuf = new char[1024];
    15. // int len;
    16. // while((len = br.read(cbuf)) != -1){
    17. // bw.write(cbuf,0,len);
    18. // // bw.flush();
    19. // }
    20. //方式二:使用String
    21. String data;
    22. while((data = br.readLine()) != null){
    23. //方法一:
    24. // bw.write(data + "\n");//data中不包含换行符
    25. //方法二:
    26. bw.write(data);//data中不包含换行符
    27. bw.newLine();//提供换行的操作
    28. }
    29. } catch (IOException e) {
    30. e.printStackTrace();
    31. } finally {
    32. //关闭资源
    33. if(bw != null){
    34. try {
    35. bw.close();
    36. } catch (IOException e) {
    37. e.printStackTrace();
    38. }
    39. }
    40. if(br != null){
    41. try {
    42. br.close();
    43. } catch (IOException e) {
    44. e.printStackTrace();
    45. }
    46. }
    47. }
    48. }

    4.6 缓冲流课后练习

    图片加密

    1. public class PicTest {
    2. //图片的加密
    3. @Test
    4. public void test1() {
    5. FileInputStream fis = null;
    6. FileOutputStream fos = null;
    7. try {
    8. fis = new FileInputStream("爱情与友情.jpg");
    9. fos = new FileOutputStream("爱情与友情secret.jpg");
    10. byte[] buffer = new byte[20];
    11. int len;
    12. while ((len = fis.read(buffer)) != -1) {
    13. //字节数组进行修改
    14. //错误的
    15. // for(byte b : buffer){
    16. // b = (byte) (b ^ 5);
    17. // }
    18. //正确的
    19. for (int i = 0; i < len; i++) {
    20. buffer[i] = (byte) (buffer[i] ^ 5);
    21. }
    22. fos.write(buffer, 0, len);
    23. }
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. } finally {
    27. if (fos != null) {
    28. try {
    29. fos.close();
    30. } catch (IOException e) {
    31. e.printStackTrace();
    32. }
    33. }
    34. if (fis != null) {
    35. try {
    36. fis.close();
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. }
    42. }
    43. //图片的解密
    44. @Test
    45. public void test2() {
    46. FileInputStream fis = null;
    47. FileOutputStream fos = null;
    48. try {
    49. fis = new FileInputStream("爱情与友情secret.jpg");
    50. fos = new FileOutputStream("爱情与友情4.jpg");
    51. byte[] buffer = new byte[20];
    52. int len;
    53. while ((len = fis.read(buffer)) != -1) {
    54. //字节数组进行修改
    55. //错误的
    56. // for(byte b : buffer){
    57. // b = (byte) (b ^ 5);
    58. // }
    59. //正确的
    60. for (int i = 0; i < len; i++) {
    61. buffer[i] = (byte) (buffer[i] ^ 5);
    62. }
    63. fos.write(buffer, 0, len);
    64. }
    65. } catch (IOException e) {
    66. e.printStackTrace();
    67. } finally {
    68. if (fos != null) {
    69. try {
    70. fos.close();
    71. } catch (IOException e) {
    72. e.printStackTrace();
    73. }
    74. }
    75. if (fis != null) {
    76. try {
    77. fis.close();
    78. } catch (IOException e) {
    79. e.printStackTrace();
    80. }
    81. }
    82. }
    83. }
    84. }

    字符统计

    1. /**
    2. * 练习3:获取文本上字符出现的次数,把数据写入文件
    3. *
    4. * 思路:
    5. * 1.遍历文本每一个字符
    6. * 2.字符出现的次数存在Map中
    7. *
    8. * Map map = new HashMap();
    9. * map.put('a',18);
    10. * map.put('你',2);
    11. *
    12. * 3.把map中的数据写入文件
    13. *
    14. */
    15. public class WordCount {
    16. /*
    17. 说明:如果使用单元测试,文件相对路径为当前module
    18. 如果使用main()测试,文件相对路径为当前工程
    19. */
    20. @Test
    21. public void testWordCount() {
    22. FileReader fr = null;
    23. BufferedWriter bw = null;
    24. try {
    25. //1.创建Map集合
    26. Map map = new HashMap();
    27. //2.遍历每一个字符,每一个字符出现的次数放到map中
    28. fr = new FileReader("dbcp.txt");
    29. int c = 0;
    30. while ((c = fr.read()) != -1) {
    31. //int 还原 char
    32. char ch = (char) c;
    33. // 判断char是否在map中第一次出现
    34. if (map.get(ch) == null) {
    35. map.put(ch, 1);
    36. } else {
    37. map.put(ch, map.get(ch) + 1);
    38. }
    39. }
    40. //3.把map中数据存在文件count.txt
    41. //3.1 创建Writer
    42. bw = new BufferedWriter(new FileWriter("wordcount.txt"));
    43. //3.2 遍历map,再写入数据
    44. Set> entrySet = map.entrySet();
    45. for (Map.Entry entry : entrySet) {
    46. switch (entry.getKey()) {
    47. case ' ':
    48. bw.write("空格=" + entry.getValue());
    49. break;
    50. case '\t'://\t表示tab 键字符
    51. bw.write("tab键=" + entry.getValue());
    52. break;
    53. case '\r'://
    54. bw.write("回车=" + entry.getValue());
    55. break;
    56. case '\n'://
    57. bw.write("换行=" + entry.getValue());
    58. break;
    59. default:
    60. bw.write(entry.getKey() + "=" + entry.getValue());
    61. break;
    62. }
    63. bw.newLine();
    64. }
    65. } catch (IOException e) {
    66. e.printStackTrace();
    67. } finally {
    68. //4.关流
    69. if (fr != null) {
    70. try {
    71. fr.close();
    72. } catch (IOException e) {
    73. e.printStackTrace();
    74. }
    75. }
    76. if (bw != null) {
    77. try {
    78. bw.close();
    79. } catch (IOException e) {
    80. e.printStackTrace();
    81. }
    82. }
    83. }
    84. }
    85. }

    5 转换流

    5.1 概述

    转换流提供了在字节流和字符流之间的转换(因FileReader没有提供特定的编码设置,需要自定义编码读取文件时,需要用到转换流-InputStreamReader)

    • Java API提供了两个转换流:
      • InputStreamReader:将InputStream转换为Reader
      • OutputStreamWriter:将Writer转换为OutputStream
    • 字节流中的数据都是字符时,转成字符流操作更高效。
    • 很多时候我们使用转换流来处理文件乱码问题。实现编码和 解码的功能。

    InputStreamReader

    • 实现将字节的输入流按指定字符集转换为字符的输入流。
    • 需要和InputStream“套接”。
    • 构造器
      • public InputStreamReader(InputStream in)
      • public InputSreamReader(InputStream in,String charsetName)

    如: Reader isr = new InputStreamReader(System.in,”gbk”);

    OutputStreamWriter

    • 实现将字符的输出流按指定字符集转换为字节的输出流。
    • 需要和OutputStream“套接”。
    • 构造器
      • public OutputStreamWriter(OutputStream out)
      • public OutputSreamWriter(OutputStream out,String charsetName)

    5.2 原理图

    这里注意:文件用什么编码存的就要用什么编码读,否则会造成乱码

    5.3 转换流读取文件

    1. /**
    2. * 处理流之二:转换流的使用
    3. * 1.转换流:属于字符流
    4. * InputStreamReader:将一个字节的输入流转换为字符的输入流
    5. * OutputStreamWriter:将一个字符的输出流转换为字节的输出流
    6. *
    7. * 2.作用:提供字节流与字符流之间的转换
    8. *
    9. * 3. 解码:字节、字节数组 --->字符数组、字符串
    10. * 编码:字符数组、字符串 ---> 字节、字节数组
    11. *
    12. *
    13. */
    14. public class InputStreamReaderTest {
    15. /*
    16. 此时处理异常的话,仍然应该使用try-catch-finally
    17. InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
    18. */
    19. @Test
    20. public void test1() throws IOException {
    21. FileInputStream fis = new FileInputStream("dbcp.txt");
    22. // InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
    23. //参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集
    24. InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//使用系统默认的字符集
    25. char[] cbuf = new char[20];
    26. int len;
    27. while((len = isr.read(cbuf)) != -1){
    28. String str = new String(cbuf,0,len);
    29. System.out.print(str);
    30. }
    31. isr.close();
    32. }
    33. }

    5.4 转换流实现文件的读入和写出

    1. /*
    2. 此时处理异常的话,仍然应该使用try-catch-finally
    3. 综合使用InputStreamReader和OutputStreamWriter
    4. */
    5. @Test
    6. public void test2() throws Exception {
    7. //1.造文件、造流
    8. File file1 = new File("dbcp.txt");
    9. File file2 = new File("dbcp_gbk.txt");
    10. FileInputStream fis = new FileInputStream(file1);
    11. FileOutputStream fos = new FileOutputStream(file2);
    12. InputStreamReader isr = new InputStreamReader(fis,"utf-8");
    13. OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
    14. //2.读写过程
    15. char[] cbuf = new char[20];
    16. int len;
    17. while((len = isr.read(cbuf)) != -1){
    18. osw.write(cbuf,0,len);
    19. }
    20. //3.关闭资源
    21. isr.close();
    22. osw.close();
    23. }

    5.5 字符编码

    编码表的由来

    计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。就将各个国家的文字用数字来表示,并一一对应,形成一张表。 这就是编码表。

    常见的编码表

    • ASCII:美国标准信息交换码。 用一个字节的7位可以表示。

    • ISO8859-1:拉丁码表。欧洲码表  用一个字节的8位表示。

    • GB2312:中国的中文编码表。最多两个字节编码所有字符

    • GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码(这里用字节的高位表示用一个字节还是两个字节表示字符,即 0110 11111表示自己就是一个独立的字符,而1011 1111 表示需要与后面的字节算到一起,表示一个完成的字符。)

    • Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。

    •  UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。

    补充

    • Unicode不完美,这里就有三个问题,一个是,我们已经知道,英文字母只用 一个字节表示就够了,第二个问题是如何才能区别Unicode和ASCII?计算机 怎么知道两个字节表示一个符号,而不是分别表示两个符号呢?第三个,如果 和GBK等双字节编码方式一样,用最高位是1或0表示两个字节和一个字节, 就少了很多值无法用于表示字符,不够表示所有字符。Unicode在很长一段时 间内无法推广,直到互联网的出现。
    • 面向传输的众多 UTF(UCS Transfer Format)标准出现了,顾名思义,UTF- 8就是每次8个位传输数据,而UTF-16就是每次16个位。这是为传输而设计的 编码,并使编码无国界,这样就可以显示全世界上所有文化的字符了。
    • Unicode只是定义了一个庞大的、全球通用的字符集,并为每个字符规定了唯 一确定的编号,具体存储成什么样的字节流,取决于字符编码方案。推荐的 Unicode编码是UTF-8和UTF-16。

    举例

    究竟Unicode是如何对应utf-8的,如下图所示,规则是将左侧16进制红框部分对应到右侧二进制红框部分,右侧红框之外的高位表示要用自己临近(后面)的哪几个字节组成一组字符。

    比如“尚”,按照Uniicode编码是5C1A,则对应到第三排,把5C1A转换为二进制,并把这16位二进制,对应到二进制的红框中。

    ps:把字符和汉字理解为商品,Unicode规定了等价交换物,如一头牛(一个字符)等价于一两黄金(一个Unicode16进制数),具体黄金能兑换多少货币(Unicode如何存储于utf-8中)看具体汇率。还要注意的是GBK采用的并不是unicode编码规则。

     综上所述:计算机底层只能识别0和1,ASCII只适合老美,别的国家不适合,因此出现了符合ANSI标准的各种编码集。Unicode做了一个大而全的字符集编码库,utf-8或者utf-16来落地。

    6 标准输入、输出流

    • System.in和System.out分别代表了系统标准的输入和输出设备

    • 默认输入设备是:键盘,输出设备是:显示器

    • System.in的类型是InputStream

    • System.out的类型是PrintStream,其是OutputStream的子类、FilterOutputStream 的子类

    • 重定向:通过System类的setIn,setOut方法对默认设备进行改变。

      • public static void setIn(InputStream in)

      • public static void setOut(PrintStream out)

    例题:

    1. import org.junit.Test;
    2. import java.io.*;
    3. /**
    4. * 其他流的使用
    5. * 1.标准的输入、输出流
    6. * 2.打印流
    7. * 3.数据流
    8. *
    9. */
    10. public class OtherStreamTest {
    11. /*
    12. 1.标准的输入、输出流
    13. 1.1
    14. System.in:标准的输入流,默认从键盘输入
    15. System.out:标准的输出流,默认从控制台输出
    16. 1.2
    17. System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。
    18. 1.3练习:
    19. 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
    20. 直至当输入“e”或者“exit”时,退出程序。
    21. 方法一:使用Scanner实现,调用next()返回一个字符串
    22. 方法二:使用System.in实现。System.in ---> 转换流 ---> BufferedReader的readLine()
    23. */
    24. public static void main(String[] args) {
    25. BufferedReader br = null;
    26. try {
    27. InputStreamReader isr = new InputStreamReader(System.in);
    28. br = new BufferedReader(isr);
    29. while (true) {
    30. System.out.println("请输入字符串:");
    31. String data = br.readLine();
    32. if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
    33. System.out.println("程序结束");
    34. break;
    35. }
    36. String upperCase = data.toUpperCase();
    37. System.out.println(upperCase);
    38. }
    39. } catch (IOException e) {
    40. e.printStackTrace();
    41. } finally {
    42. if (br != null) {
    43. try {
    44. br.close();
    45. } catch (IOException e) {
    46. e.printStackTrace();
    47. }
    48. }
    49. }
    50. }

    7 打印流

    • 实现将基本数据类型的数据格式转化为字符串输出
    • 打印流:PrintStream和PrintWriter
      • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
      • PrintStream和PrintWriter的输出不会抛出IOException异常
      • PrintStream和PrintWriter有自动flush功能
      • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
      • System.out返回的是PrintStream的实例
    1. /*
    2. 2. 打印流:PrintStream 和PrintWriter
    3. 2.1 提供了一系列重载的print() 和 println()
    4. 2.2 练习:
    5. */
    6. @Test
    7. public void test2() {
    8. PrintStream ps = null;
    9. try {
    10. FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
    11. // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
    12. ps = new PrintStream(fos, true);
    13. if (ps != null) {// 把标准输出流(控制台输出)改成文件
    14. System.setOut(ps);
    15. }
    16. for (int i = 0; i <= 255; i++) { // 输出ASCII字符
    17. System.out.print((char) i);
    18. if (i % 50 == 0) { // 每50个数据一行
    19. System.out.println(); // 换行
    20. }
    21. }
    22. } catch (FileNotFoundException e) {
    23. e.printStackTrace();
    24. } finally {
    25. if (ps != null) {
    26. ps.close();
    27. }
    28. }
    29. }

    8 数据流

    • 为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
    • 数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
      • DataInputStream 和 DataOutputStream
      •  分别“套接”在 InputStream 和 OutputStream 子类的流上
    • DataInputStream中的方法
    boolean readBoolean() byte readByte()     
    char readChar()                float readFloat()
    double readDouble() short readShort()
    long readLong() int readInt() 
    String readUTF() void readFully(byte[] b)
    • DataOutputStream中的方法
    • 将上述的方法的read改为相应的write即可。
    1. /*
    2. 3. 数据流
    3. 3.1 DataInputStream 和 DataOutputStream
    4. 3.2 作用:用于读取或写出基本数据类型的变量或字符串
    5. 练习:将内存中的字符串、基本数据类型的变量写出到文件中。
    6. 注意:处理异常的话,仍然应该使用try-catch-finally.
    7. */
    8. @Test
    9. public void test3() throws IOException {
    10. //1.
    11. DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
    12. //2.
    13. dos.writeUTF("小李");
    14. dos.flush();//刷新操作,将内存中的数据写入文件
    15. dos.writeInt(23);
    16. dos.flush();
    17. dos.writeBoolean(true);
    18. dos.flush();
    19. //3.
    20. dos.close();
    21. }
    22. /*
    23. 将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
    24. 注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
    25. */
    26. @Test
    27. public void test4() throws IOException {
    28. //1.
    29. DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
    30. //2.
    31. String name = dis.readUTF();
    32. int age = dis.readInt();
    33. boolean isMale = dis.readBoolean();
    34. System.out.println("name = " + name);
    35. System.out.println("age = " + age);
    36. System.out.println("isMale = " + isMale);
    37. //3.
    38. dis.close();
    39. }

    9 对象流

    9.1 对象序列化概念

    • ObjectInputStream和OjbectOutputSteam
      • 用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
      • 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
      • 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
      • ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
    • 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从 而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传 输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原 来的Java对象
    • 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据, 使其在保存和传输时可被还原
    • 序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返 回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是 JavaEE 平台的基础
    • 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可 序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。 否则,会抛出NotSerializableException异常
      • Serializable
      • Externalizable

    9.2 对象流序列化与反序列化字符串操作

    1. public class ObjectInputOutputStreamTest {
    2. /**
    3. * 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    4. * 使用ObjectOutputStream实现
    5. */
    6. @Test
    7. public void test() {
    8. ObjectOutputStream oos = null;
    9. try {
    10. //创造流
    11. oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
    12. //制造对象
    13. oos.writeObject(new String("北京欢迎你"));
    14. //刷新操作
    15. oos.flush();
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. } finally {
    19. if (oos != null) {
    20. //3.关闭流
    21. try {
    22. oos.close();
    23. } catch (IOException e) {
    24. e.printStackTrace();
    25. }
    26. }
    27. }
    28. }
    29. /**
    30. * 反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    31. * 使用ObjectInputStream来实现
    32. */
    33. @Test
    34. public void test2() {
    35. ObjectInputStream ois = null;
    36. try {
    37. ois = new ObjectInputStream(new FileInputStream("object.dat"));
    38. Object obj = ois.readObject();
    39. String str = (String) obj;
    40. System.out.println(str);
    41. } catch (IOException e) {
    42. e.printStackTrace();
    43. } catch (ClassNotFoundException e) {
    44. e.printStackTrace();
    45. } finally {
    46. if (ois != null) {
    47. try {
    48. ois.close();
    49. } catch (IOException e) {
    50. e.printStackTrace();
    51. }
    52. }
    53. }
    54. }
    55. }

    9.3 自定义类实现序列化与反序列化操作

    • 若某个类实现了 Serializable 接口,该类的对象就是可序列化的:
      • 创建一个 ObjectOutputStream
      • 调用 ObjectOutputStream 对象的 writeObject(对象) 方法输出可序列化对象
      • 注意写出一次,操作flush()一次
    • 反序列化
      • 创建一个 ObjectInputStream
      • 调用 readObject() 方法读取流中的对象
    • 强调:如果某个类的属性不是基本数据类型或 String 类型,而是另一个 引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的 Field 的类也不能序列化

    Persion.java

    1. package com.atguigu.java;
    2. import java.io.Serializable;
    3. /**
    4. * Person需要满足如下的要求,方可序列化
    5. * 1.需要实现接口:Serializable
    6. * 2.当前类提供一个全局常量:serialVersionUID
    7. * 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性
    8. * 也必须是可序列化的。(默认情况下,基本数据类型可序列化)
    9. *
    10. *
    11. * 补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
    12. *
    13. */
    14. public class Person implements Serializable{
    15. public static final long serialVersionUID = 475463534532L;
    16. private String name;
    17. private int age;
    18. private int id;
    19. public Person(String name, int age,) {
    20. this.name = name;
    21. this.age = age;
    22. }
    23. public Person(String name, int age) {
    24. this.name = name;
    25. this.age = age;
    26. }
    27. @Override
    28. public String toString() {
    29. return "Person{" +
    30. "name='" + name + '\'' +
    31. ", age=" + age
    32. '}';
    33. }
    34. public String getName() {
    35. return name;
    36. }
    37. public void setName(String name) {
    38. this.name = name;
    39. }
    40. public int getAge() {
    41. return age;
    42. }
    43. public void setAge(int age) {
    44. this.age = age;
    45. }
    46. public Person(String name, int age) {
    47. this.name = name;
    48. this.age = age;
    49. }
    50. public Person() {
    51. }
    52. }
    53. }

    demo

    1. public class ObjectInputOutputStreamTest {
    2. /*
    3. 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    4. 使用ObjectOutputStream实现
    5. */
    6. @Test
    7. public void testObjectOutputStream(){
    8. ObjectOutputStream oos = null;
    9. try {
    10. //1.
    11. oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
    12. //2.
    13. oos.writeObject(new String("北京欢迎你"));
    14. oos.flush();//刷新操作
    15. oos.writeObject(new Person("张三",23));
    16. oos.flush();
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. } finally {
    20. if(oos != null){
    21. //3.
    22. try {
    23. oos.close();
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. }
    29. }
    30. /*
    31. 反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    32. 使用ObjectInputStream来实现
    33. */
    34. @Test
    35. public void testObjectInputStream(){
    36. ObjectInputStream ois = null;
    37. try {
    38. ois = new ObjectInputStream(new FileInputStream("object.dat"));
    39. Object obj = ois.readObject();
    40. String str = (String) obj;
    41. Person p = (Person) ois.readObject();
    42. System.out.println(str);
    43. System.out.println(p);
    44. } catch (IOException e) {
    45. e.printStackTrace();
    46. } catch (ClassNotFoundException e) {
    47. e.printStackTrace();
    48. } finally {
    49. if(ois != null){
    50. try {
    51. ois.close();
    52. } catch (IOException e) {
    53. e.printStackTrace();
    54. }
    55. }
    56. }
    57. }
    58. }

    9.3 serialVersionUID的理解

    • 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
      • private static final long serialVersionUID;
      • serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象 进行版本控制,有关各版本反序列化时是否兼容。
      • 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自 动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议, 显式声明。
    • 简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验 证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的 serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同 就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异 常。(InvalidCastException)

    Person类

    1. public class Person implements Serializable{
    2. public static final long serialVersionUID = 475463534532L;
    3. private String name;
    4. private int age;
    5. private int id;
    6. public Person(String name, int age, int id) {
    7. this.name = name;
    8. this.age = age;
    9. this.id = id;
    10. }
    11. public Person(String name, int age, int id) {
    12. this.name = name;
    13. this.age = age;
    14. this.id = id;
    15. }
    16. @Override
    17. public String toString() {
    18. return "Person{" +
    19. "name='" + name + '\'' +
    20. ", age=" + age +
    21. ", id=" + id
    22. '}';
    23. }
    24. public int getId() {
    25. return id;
    26. }
    27. public void setId(int id) {
    28. this.id = id;
    29. }
    30. public String getName() {
    31. return name;
    32. }
    33. public void setName(String name) {
    34. this.name = name;
    35. }
    36. public int getAge() {
    37. return age;
    38. }
    39. public void setAge(int age) {
    40. this.age = age;
    41. }
    42. public Person(String name, int age) {
    43. this.name = name;
    44. this.age = age;
    45. }
    46. public Person() {
    47. }
    48. }
    49. }

    demo

    1. public class ObjectInputOutputStreamTest {
    2. /*
    3. 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    4. 使用ObjectOutputStream实现
    5. */
    6. @Test
    7. public void testObjectOutputStream(){
    8. ObjectOutputStream oos = null;
    9. try {
    10. //1.
    11. oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
    12. //2.
    13. oos.writeObject(new String("我爱北京天安门"));
    14. oos.flush();//刷新操作
    15. oos.writeObject(new Person("王铭",23));
    16. oos.flush();
    17. oos.writeObject(new Person("张学良",23));
    18. oos.flush();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. } finally {
    22. if(oos != null){
    23. //3.
    24. try {
    25. oos.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }
    31. }
    32. /*
    33. 反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    34. 使用ObjectInputStream来实现
    35. */
    36. @Test
    37. public void testObjectInputStream(){
    38. ObjectInputStream ois = null;
    39. try {
    40. ois = new ObjectInputStream(new FileInputStream("object.dat"));
    41. Object obj = ois.readObject();
    42. String str = (String) obj;
    43. Person p = (Person) ois.readObject();
    44. System.out.println(str);
    45. System.out.println(p);
    46. } catch (IOException e) {
    47. e.printStackTrace();
    48. } catch (ClassNotFoundException e) {
    49. e.printStackTrace();
    50. } finally {
    51. if(ois != null){
    52. try {
    53. ois.close();
    54. } catch (IOException e) {
    55. e.printStackTrace();
    56. }
    57. }
    58. }
    59. }
    60. }

    总结:如果不显示的指定serialVersionUID,就会生成一个隐式的serialVersionUID,在序列化到反序列化过程中,如果类发生变化,会导致反序列化失败,如果显示的进行指定了serialVersionUID,即使类发生了变化,也能反序列化成功。

    9.4 自定义类可序列化的其他要求

    除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)

    Person类

    1. /**
    2. * Person需要满足如下的要求,方可序列化
    3. * 1.需要实现接口:Serializable
    4. * 2.当前类提供一个全局常量:serialVersionUID
    5. * 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性
    6. * 也必须是可序列化的。(默认情况下,基本数据类型可序列化)
    7. *
    8. *
    9. * 补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
    10. *
    11. */
    12. public class Person implements Serializable{
    13. public static final long serialVersionUID = 475463534532L;
    14. private String name;
    15. private int age;
    16. private int id;
    17. private Account acct;
    18. public Person(String name, int age, int id) {
    19. this.name = name;
    20. this.age = age;
    21. this.id = id;
    22. }
    23. public Person(String name, int age, int id, Account acct) {
    24. this.name = name;
    25. this.age = age;
    26. this.id = id;
    27. this.acct = acct;
    28. }
    29. @Override
    30. public String toString() {
    31. return "Person{" +
    32. "name='" + name + '\'' +
    33. ", age=" + age +
    34. ", id=" + id +
    35. ", acct=" + acct +
    36. '}';
    37. }
    38. public int getId() {
    39. return id;
    40. }
    41. public void setId(int id) {
    42. this.id = id;
    43. }
    44. public String getName() {
    45. return name;
    46. }
    47. public void setName(String name) {
    48. this.name = name;
    49. }
    50. public int getAge() {
    51. return age;
    52. }
    53. public void setAge(int age) {
    54. this.age = age;
    55. }
    56. public Person(String name, int age) {
    57. this.name = name;
    58. this.age = age;
    59. }
    60. public Person() {
    61. }
    62. }
    63. // 也需要序列化
    64. class Account implements Serializable{
    65. public static final long serialVersionUID = 4754534532L;
    66. private double balance;
    67. @Override
    68. public String toString() {
    69. return "Account{" +
    70. "balance=" + balance +
    71. '}';
    72. }
    73. public double getBalance() {
    74. return balance;
    75. }
    76. public void setBalance(double balance) {
    77. this.balance = balance;
    78. }
    79. public Account(double balance) {
    80. this.balance = balance;
    81. }
    82. }

    demo

    1. public class ObjectInputOutputStreamTest {
    2. /*
    3. 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    4. 使用ObjectOutputStream实现
    5. */
    6. @Test
    7. public void testObjectOutputStream(){
    8. ObjectOutputStream oos = null;
    9. try {
    10. //1.
    11. oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
    12. //2.
    13. oos.writeObject(new String("我爱北京天安门"));
    14. oos.flush();//刷新操作
    15. oos.writeObject(new Person("王铭",23));
    16. oos.flush();
    17. oos.writeObject(new Person("张学良",23,1001,new Account(5000)));
    18. oos.flush();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. } finally {
    22. if(oos != null){
    23. //3.
    24. try {
    25. oos.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }
    31. }
    32. /*
    33. 反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    34. 使用ObjectInputStream来实现
    35. */
    36. @Test
    37. public void testObjectInputStream(){
    38. ObjectInputStream ois = null;
    39. try {
    40. ois = new ObjectInputStream(new FileInputStream("object.dat"));
    41. Object obj = ois.readObject();
    42. String str = (String) obj;
    43. Person p = (Person) ois.readObject();
    44. Person p1 = (Person) ois.readObject();
    45. System.out.println(str);
    46. System.out.println(p);
    47. System.out.println(p1);
    48. } catch (IOException e) {
    49. e.printStackTrace();
    50. } catch (ClassNotFoundException e) {
    51. e.printStackTrace();
    52. } finally {
    53. if(ois != null){
    54. try {
    55. ois.close();
    56. } catch (IOException e) {
    57. e.printStackTrace();
    58. }
    59. }
    60. }
    61. }
    62. }

    10 随机存取文件流

    10.1 RandomAccessFile实现数据的读写操作

    • RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并 且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也 可以写。
    • RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意 地方来读、写文件
      • 支持只访问文件的部分内容
      • 可以向已存在的文件后追加内容
    • RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。 RandomAccessFile 类对象可以自由移动记录指针:
      • long getFilePointer():获取文件记录指针的当前位置
      • void seek(long pos):将文件记录指针定位到 pos 位置
    • 构造器
      • public RandomAccessFile(File file, String mode)
      • public RandomAccessFile(String name, String mode)
    • 创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指 定 RandomAccessFile 的访问模式:
      • r: 以只读方式打开
      • rw:打开以便读取和写入
      • rwd:打开以便读取和写入;同步文件内容的更新
      • rws:打开以便读取和写入;同步文件内容和元数据的更新
    • 如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件, 如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不 存在则会去创建文件,如果存在则不会创建。
    1. /**
    2. * RandomAccessFile的使用
    3. * 1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
    4. * 2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
    5. *
    6. * 3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
    7. * 如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
    8. *
    9. * 4. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
    10. *
    11. */
    12. public class RandomAccessFileTest {
    13. @Test
    14. public void test1() {
    15. RandomAccessFile raf1 = null;
    16. RandomAccessFile raf2 = null;
    17. try {
    18. //1.
    19. raf1 = new RandomAccessFile(new File("爱情与友情.jpg"),"r");
    20. raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");
    21. //2.
    22. byte[] buffer = new byte[1024];
    23. int len;
    24. while((len = raf1.read(buffer)) != -1){
    25. raf2.write(buffer,0,len);
    26. }
    27. } catch (IOException e) {
    28. e.printStackTrace();
    29. } finally {
    30. //3.
    31. if(raf1 != null){
    32. try {
    33. raf1.close();
    34. } catch (IOException e) {
    35. e.printStackTrace();
    36. }
    37. }
    38. if(raf2 != null){
    39. try {
    40. raf2.close();
    41. } catch (IOException e) {
    42. e.printStackTrace();
    43. }
    44. }
    45. }
    46. }
    47. }
    48. @Test
    49. public void test2() throws IOException {
    50. RandomAccessFile raf1 = new RandomAccessFile("hello1.txt","rw");
    51. // 覆盖操作,默认指针从0开始写,写完后,如果文件中有多余的内容仍存在,不会被擦除
    52. raf1.write("xyz".getBytes());
    53. raf1.close();
    54. }
    55. }

    10.2 RandomAccessFile实现数据的插入

    1. /**
    2. * RandomAccessFile的使用
    3. * 1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
    4. * 2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
    5. *
    6. * 3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
    7. * 如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
    8. *
    9. * 4. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
    10. */
    11. public class RandomAccessFileTest {
    12. /*
    13. 使用RandomAccessFile实现数据的插入效果
    14. */
    15. @Test
    16. public void test3() throws IOException {
    17. RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
    18. raf1.seek(3);//将指针调到角标为3的位置
    19. //保存指针3后面的所有数据到StringBuilder中
    20. StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
    21. byte[] buffer = new byte[20];
    22. int len;
    23. while((len = raf1.read(buffer)) != -1){
    24. builder.append(new String(buffer,0,len)) ;
    25. }
    26. //调回指针,写入“xyz”
    27. raf1.seek(3);
    28. raf1.write("xyz".getBytes());
    29. //将StringBuilder中的数据写入到文件中
    30. raf1.write(builder.toString().getBytes());
    31. raf1.close();
    32. //思考:将StringBuilder替换为ByteArrayOutputStream
    33. }
    34. }

    10.3 扩展

    可以用RandomAccessFile这个类,来实现一个多线程断点下载的功能, 用过下载工具的朋友们都知道,下载前都会建立两个临时文件,一个是与 被下载文件大小相同的空文件,另一个是记录文件指针的位置文件,每次 暂停的时候,都会保存上一次的指针,然后断点下载的时候,会继续从上 一次的地方下载,从而实现断点下载或上传的功能。

    11 NIO.2中Path、Paths、Files类的使用

    11.1 概述

    • Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新 的IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目 的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于 通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。
    • Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网 络编程NIO。
      • |-----java.nio.channels.Channel
        • |-----FileChannel:处理本地文件
        • |-----SocketChannel:TCP网络编程的客户端的Channel
        • |-----ServerSocketChannel:TCP网络编程的服务器端的Channel
        • |-----DatagramChannel:UDP网络编程中发送端和接收端的Channel
    • 随着 JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对 文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。 因为 NIO 提供的一些功能,NIO已经成为文件处理中越来越重要 的部分。
    • 早期的Java只提供了一个File类来访问文件系统,但File类的功能比较有限,所 提供的方法性能也不高。而且,大多数方法在出错时仅返回失败,并不会提供异 常信息。
    • NIO. 2为了弥补这种不足,引入了Path接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。Path可以看成是File类的升级版本,实际引用的资 源也可以不存在。
    • 在以前IO操作都是这样写的:
    1. import java.io.File;
    2. File file = new File("index.html");
    • 但在Java7 中,我们可以这样写:
    1. import java.nio.file.Path;
    2. import java.nio.file.Paths;
    3. Path path = Paths.get("index.html");
    • 同时,NIO.2在java.nio.file包下还提供了Files、Paths工具类,Files包含 了大量静态的工具方法来操作文件;Paths则包含了两个返回Path的静态 工厂方法。
    • Paths 类提供的静态 get() 方法用来获取 Path 对象:
      • static Path get(String first, String ... more) : 用于将多个字符串串连成路径
      • static Path get(URI uri): 返回指定uri对应的Path路径

    10.2 Path接口

    1. String toString() : 返回调用 Path 对象的字符串表示形式
    2. boolean startsWith(String path) : 判断是否以 path 路径开始
    3. boolean endsWith(String path) : 判断是否以 path 路径结束
    4. boolean isAbsolute() : 判断是否是绝对路径
    5. Path getParent() :返回Path对象包含整个路径,不包含 Path 对象指定的文件路径
    6. Path getRoot() :返回调用 Path 对象的根路径
    7. Path getFileName() : 返回与调用 Path 对象关联的文件名
    8. int getNameCount() : 返回Path 根目录后面元素的数量
    9. Path getName(int idx) : 返回指定索引位置 idx 的路径名称
    10. Path toAbsolutePath() : 作为绝对路径返回调用 Path 对象
    11. Path resolve(Path p) :合并两个路径,返回合并后的路径对应的Path对象
    12. File toFile(): 将Path转化为File类的对象

    10.3 Files 类

    1. 常用方法:
    2. Path copy(Path src, Path dest, CopyOption ... how) : 文件的复制
    3. Path createDirectory(Path path, FileAttribute ... attr) : 创建一个目录
    4. Path createFile(Path path, FileAttribute ... arr) : 创建一个文件
    5. void delete(Path path) : 删除一个文件/目录,如果不存在,执行报错
    6. void deleteIfExists(Path path) : Path对应的文件/目录如果存在,执行删除
    7. Path move(Path src, Path dest, CopyOption...how) : 将 src 移动到 dest 位置  long size(Path path) : 返回 path 指定文件的大小
    8. 用于判断:
    9. boolean exists(Path path, LinkOption ... opts) : 判断文件是否存在
    10. boolean isDirectory(Path path, LinkOption ... opts) : 判断是否是目录
    11. boolean isRegularFile(Path path, LinkOption ... opts) : 判断是否是文件  boolean isHidden(Path path) : 判断是否是隐藏文件
    12. boolean isReadable(Path path) : 判断文件是否可读
    13. boolean isWritable(Path path) : 判断文件是否可写
    14. boolean notExists(Path path, LinkOption ... opts) : 判断文件是否不存在
    15. 用于操作内容:
    16. SeekableByteChannel newByteChannel(Path path, OpenOption...how) : 获取与指定文件的连
    17. 接,how 指定打开方式。
    18. DirectoryStream newDirectoryStream(Path path) : 打开 path 指定的目录
    19. InputStream newInputStream(Path path, OpenOption...how):获取 InputStream 对象
    20. OutputStream newOutputStream(Path path, OpenOption...how) : 获取 OutputStream 对象

    10.4  FileUtils

    1. // 删除文件夹及目录下文件
    2. File dirFile = new File(uploadDir);
    3. FileUtils.deleteDirectory(dirFile)

  • 相关阅读:
    Idea下面git的使用:变基、合并、优选、还原提交、重置、回滚、补丁
    弘辽科技:拼多多商品发布被驳回是为什么?被驳回怎么办?
    Android 10.0 系统开启和关闭黑白模式主题功能实现
    图神经网络torch_geometric库的使用
    计算机毕业设计springboot+vue基本医院公众号建设推动医疗卫生服务现状研究
    TM-30 计算软件 (Excel图表显示版本)
    5.Mybatis 基础知识
    es入门教程
    Python搭建虚拟环境
    表象变换与矩阵元
  • 原文地址:https://blog.csdn.net/danxiaodeshitou/article/details/133976553