言成言成啊 | Kit Chen's Blog

File类与IO流

发布于2019-12-10 19:46:06,更新于2020-07-11 12:15:54,标签:java  转载随意,文章会持续修订,请注明来源地址:https://meethigher.top/blog

第一章 File类

1.1 概述

java.io.File 类是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作。

具体操作

  • 创建文件/文件夹
  • 删除文件/文件夹
  • 获取文件/文件夹
  • 判断文件/文件夹是否存在
  • 对文件进行遍历
  • 获取文件的大小

File类是一个与系统无关的类,任何的操作系统都可以使用这个类中的方法。

file文件

directory文件夹/目录

path路径

static String pathSeparator与系统有关的路径分隔符,为了方便,它被表示为一个字符串。

static char pathSeparatorChar与系统有关的路径分隔符

路径分隔符,windows;linux:

static String separator与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串

static char separatorChar与系统有关的默认名称分隔符

文件名称分割符,windows\linux/

1.2 构造方法

  • public File(String pathname) :通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
  • public File(String parent, String child) :从父路径名字符串和子路径名字符串创建新的 File实例。
  • public File(File parent, String child) :从父抽象路径名和子路径名字符串创建新的 File实例。
  • 构造举例,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 文件路径名
String pathname = "D:\\aaa.txt";
File file1 = new File(pathname);

// 文件路径名
String pathname2 = "D:\\aaa\\bbb.txt";
File file2 = new File(pathname2);

// 通过父路径和子路径字符串
String parent = "d:\\aaa";
String child = "bbb.txt";
File file3 = new File(parent, child);

// 通过父级File对象和子路径字符串
File parentDir = new File("d:\\aaa");
String child = "bbb.txt";
File file4 = new File(parentDir, child);

小贴士:

  1. 一个File对象代表硬盘中实际存在的一个文件或者目录。
  2. 无论该路径下是否存在文件或者目录,都不影响File对象的创建。

1.3 常用方法

获取功能的方法

  • public String getAbsolutePath() :返回此File的绝对路径名字符串。

  • public String getPath() :将此File转换为路径名字符串。

  • public String getName() :返回由此File表示的文件或目录的名称。

  • public long length() :返回由此File表示的文件的长度。

注意:length()获取的是构造方法指定的文件的大小,以字节为单位。文件夹是没有大小概念的,没法获取文件夹大小;如果构造方法中给出的路径是不存在,或者是假的,那么length方法返回0

方法演示,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class FileGet {
public static void main(String[] args) {
File f = new File("d:/aaa/bbb.java");
System.out.println("文件绝对路径:"+f.getAbsolutePath());
System.out.println("文件构造路径:"+f.getPath());
System.out.println("文件名称:"+f.getName());
System.out.println("文件长度:"+f.length()+"字节");

File f2 = new File("d:/aaa");
System.out.println("目录绝对路径:"+f2.getAbsolutePath());
System.out.println("目录构造路径:"+f2.getPath());
System.out.println("目录名称:"+f2.getName());
System.out.println("目录长度:"+f2.length());
}
}
输出结果:
文件绝对路径:d:\aaa\bbb.java
文件构造路径:d:\aaa\bbb.java
文件名称:bbb.java
文件长度:636字节

目录绝对路径:d:\aaa
目录构造路径:d:\aaa
目录名称:aaa
目录长度:4096

API中说明:length(),表示文件的长度。但是File对象表示目录,则返回值未指定。

绝对路径和相对路径

  • 绝对路径:从盘符开始的路径,这是一个完整的路径。
  • 相对路径:相对于项目目录的路径,这是一个便捷的路径,开发中经常使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FilePath {
public static void main(String[] args) {
// D盘下的bbb.java文件
File f = new File("D:\\bbb.java");
System.out.println(f.getAbsolutePath());

// 项目下的bbb.java文件
File f2 = new File("bbb.java");
System.out.println(f2.getAbsolutePath());
}
}
输出结果:
D:\bbb.java
D:\idea_project_test4\bbb.java

注意事项:

  1. 路径他是不区分大小写的。
  2. 路径中的文件名称分隔符,windows是\,是转义字符,所以在使用的时候,应该用\\

判断功能的方法

  • public boolean exists() :此File表示的文件或目录是否实际存在。
  • public boolean isDirectory() :此File表示的是否为目录。
  • public boolean isFile() :此File表示的是否为文件。

注意事项:

  1. 电脑硬盘中只有文件/文件夹,两个是互斥的
  2. 使用前提,路径存在,否则返回false

方法演示,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FileIs {
public static void main(String[] args) {
File f = new File("d:\\aaa\\bbb.java");
File f2 = new File("d:\\aaa");
// 判断是否存在
System.out.println("d:\\aaa\\bbb.java 是否存在:"+f.exists());
System.out.println("d:\\aaa 是否存在:"+f2.exists());
// 判断是文件还是目录
System.out.println("d:\\aaa 文件?:"+f2.isFile());
System.out.println("d:\\aaa 目录?:"+f2.isDirectory());
}
}
输出结果:
d:\aaa\bbb.java 是否存在:true
d:\aaa 是否存在:true
d:\aaa 文件?:false
d:\aaa 目录?:true

创建删除功能的方法

  • public boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。
  • public boolean delete() :删除由此File表示的文件或目录。
  • public boolean mkdir() :创建由此File表示的目录。
  • public boolean mkdirs() :创建由此File表示的目录,包括任何必需但不存在的父目录。

方法演示,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class FileCreateDelete {
public static void main(String[] args) throws IOException {
// 文件的创建
File f = new File("aaa.txt");
System.out.println("是否存在:"+f.exists()); // false
System.out.println("是否创建:"+f.createNewFile()); // true
System.out.println("是否存在:"+f.exists()); // true

// 目录的创建
File f2= new File("newDir");
System.out.println("是否存在:"+f2.exists());// false
System.out.println("是否创建:"+f2.mkdir()); // true
System.out.println("是否存在:"+f2.exists());// true

// 创建多级目录
File f3= new File("newDira\\newDirb");
System.out.println(f3.mkdir());// false
File f4= new File("newDira\\newDirb");
System.out.println(f4.mkdirs());// true

// 文件的删除
System.out.println(f.delete());// true

// 目录的删除
System.out.println(f2.delete());// true
System.out.println(f4.delete());// false
}
}

API中说明:delete方法,如果此File表示目录,则目录必须为空才能删除。delete方法是直接在硬盘上删除文件/文件夹,不走回收站,删除要谨慎。

1.4 目录的遍历

  • public String[] list() :返回一个String数组,表示该File目录中的所有子文件或目录。
  • public File[] listFiles() :返回一个File数组,表示该File目录中的所有的子文件或目录。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class FileFor {
public static void main(String[] args) {
File dir = new File("d:\\java_code");

//获取当前目录下的文件以及文件夹的名称。
String[] names = dir.list();
for(String name : names){
System.out.println(name);
}
//获取当前目录下的文件以及文件夹对象,只要拿到了文件对象,那么就可以获取更多信息
File[] files = dir.listFiles();
for (File file : files) {
System.out.println(file);
}
}
}

小贴士:

调用listFiles方法的File对象,表示的必须是实际存在的目录,否则返回null,无法进行遍历。

隐藏文件以及隐藏文件夹同样也能被遍历

第二章 递归

2.1 概述

  • 递归:指在当前方法内调用自己的这种现象。
  • 递归的分类:
    • 递归分为两种,直接递归和间接递归。
    • 直接递归称为方法自身调用自己。
    • 间接递归可以A方法调用B方法,B方法调用C方法,C方法调用A方法。
  • 注意事项
    • 当一个方法调用其他方法的时候,被调用的方法没有执行完毕,当前方法会一直等待调用的方法执行完毕,才会继续执行。
    • 递归一定要有条件限定,保证递归能够停止下来,否则会发生栈内存溢出。
    • 在递归中虽然有限定条件,但是递归次数不能太多。否则也会发生栈内存溢出。
    • 构造方法,禁止递归
  • 递归的使用前提:
    • 当调用方法的时候,方法的主体保持不变,每次调用方法的参数不同,可以使用递归。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Demo01Recursive {
public static void main(String[] args) {
// a();
b(1);
}
/*
* 编译报错
* 构造方法是创建对象使用的,一直递归会导致内存中有无数多个对象,直接编译报错。
*/
// public Demo01Recursive() {
// Demo01Recursive();
// }
/*
* 在递归中虽然有限定条件,但是递归次数不能太多。否则也会发生栈内存溢出。
*/
public static void b(int a) {
System.out.println(a);
if(a==20) {//设置成20000就会挂了
return;//结束方法
}
b(++a);
}
/*
* 递归要有条件限定,保证递归能够停下来,否则会发生栈内存溢出
* java.lang.StackOverFlowError
*
*/
public static void a() {
System.out.println("a方法");
a();
}
}

2.2 递归累加求和

计算1 ~ n的和

分析:num的累和 = num + (num-1)的累和,所以可以把累和的操作定义成一个方法,递归调用。

注意:使用递归求和,main方法调用sum方法,sum方法会一直调用sum方法,导致在内存中有多个sum方法(频繁的创建方法,调用方法,销毁方法)效率低下。所以如果只是求和,不推荐用递归,for循环即可

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Demo02Recursive {
public static void main(String[] args) {
System.out.println(sum(3));

System.out.println(sum(100));
}
public static int sum(int n) {
//获取到1的时候结束
if(n==1) {
return 1;
}
//获取下一个被加的数字
return n+sum(n-1);
}
}

代码执行图解

小贴士:递归一定要有条件限定,保证递归能够停止下来,次数不要太多,否则会发生栈内存溢出。

2.3 递归求阶乘

  • 阶乘:所有小于及等于该数的正整数的积。
1
n的阶乘:n! = n * (n-1) *...* 3 * 2 * 1

分析:这与累和类似,只不过换成了乘法运算,学员可以自己练习,需要注意阶乘值符合int类型的范围。

1
推理得出:n! = n * (n-1)!

代码实现

1
2
3
4
5
6
7
8
9
10
11
public class Demo03Recursive {
public static void main(String[] args) {
System.out.println(factorial(3));
}
public static int factorial(int n) {
if(n==1) {
return 1;
}
return n*factorial(n-1);
}
}

2.4 递归打印多级目录

分析:多级目录的打印,就是当目录的嵌套。遍历之前,无从知道到底有多少级目录,所以我们还是要使用递归实现。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Demo04RecursivePrintDirectory {
public static void main(String[] args) throws IOException {
File f=new File("C:\\users\\kitchen\\desktop\\abc");
getAllFile(f);
}
/*
* 定义一个方法,参数传递File类型的目录
* 方法中对目录进行遍历
* abc\b
* abc\b\b.txt
* abc\b\b.java
*/
public static void getAllFile(File dir) {
File[] file=dir.listFiles();
for(File f:file) {
if(!f.isFile()) {
System.out.println(f);
getAllFile(f);
}else {
System.out.println(f);
}
}
}
}

第三章 综合案例

3.1 文件搜索

搜索D:\aaa 目录中的.java 文件。

分析

  1. 目录搜索,无法判断多少级目录,所以使用递归,遍历所有目录。
  2. 遍历目录时,获取的子文件,通过文件名称,判断是否符合条件。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Demo05Recursive {
public static void main(String[] args) {
File file=new File("C:\\users\\kitchen\\desktop\\abc");
searchJava(file);
}
/*
* 搜索.java文件
*/
public static void searchJava(File dir) {
File[] file=dir.listFiles();
for(File f:file) {
if(!f.isFile()) {
searchJava(f);
}else {
String str=f.toString();
if(str.toLowerCase().endsWith(".java")) {
System.out.println(str);
}
}
}
}
}

3.2 文件过滤器优化

java.io.FileFilter是一个接口,是File的过滤器。 该接口的对象可以传递给File类的listFiles(FileFilter) 作为参数, 接口中只有一个方法。

boolean accept(File pathname) :测试pathname是否应该包含在当前File目录中,符合则返回true。

分析

  1. 接口作为参数,需要传递子类对象,重写其中方法。我们选择匿名内部类方式,比较简单。
  2. accept方法,参数为File,表示当前File下所有的子文件和子目录。保留住则返回true,过滤掉则返回false。保留规则:
    1. 要么是.java文件。
    2. 要么是目录,用于继续遍历。
  3. 通过过滤器的作用,listFiles(FileFilter)返回的数组元素中,子文件对象都是符合条件的,可以直接打印。

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Demo06FileFilter {
public static void main(String[] args) {
File file=new File("C:\\users\\kitchen\\desktop\\abc");
searchJava(file);
}
public static void searchJava(File dir) {
File[] file=dir.listFiles(new FileFilter() {

@Override
public boolean accept(File pathname) {
/*
* 过滤的规则:
* 在accept方法中,判断File对象是否是以.java为结尾,或者是否是一个目录
* 是就返回true
* 不是就返回false,false就表示该路径被过滤掉了
*/
return pathname.getName().toLowerCase().endsWith(".java")||pathname.isDirectory();
}
});
for(File f:file) {
if(f.isFile()) {
System.out.println(f);
}else {
searchJava(f);
}
}

}
}

3.3 Lambda优化

分析:FileFilter是只有一个方法的接口,因此可以用lambda表达式简写。

lambda格式:

1
()->{ }

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Demo06FileFilter {
public static void main(String[] args) {
File file=new File("C:\\users\\kitchen\\desktop\\abc");
searchJava(file);
}
public static void searchJava(File dir) {
// File[] file=dir.listFiles(new FileFilter() {
//
// @Override
// public boolean accept(File pathname) {
// /*
// * 过滤的规则:
// * 在accept方法中,判断File对象是否是以.java为结尾,或者是否是一个目录
// * 是就返回true
// * 不是就返回false,false就表示该路径被过滤掉了
// */
// return pathname.getName().toLowerCase().endsWith(".java")||pathname.isDirectory();
// }
// });

//Lambda优化,采用Lambda的省略格式
File[] file=dir.listFiles((d,pathname)->new File(d,pathname).isDirectory()||pathname.toLowerCase().endsWith(".java")
);
for(File f:file) {
if(f.isFile()) {
System.out.println(f);
}else {
searchJava(f);
}
}

}
}

第四章 IO概述

4.1 什么是IO

生活中,你肯定经历过这样的场景。当你编辑一个文本文件,忘记了ctrl+s ,可能文件就白白编辑了。当你电脑上插入一个U盘,可以把一个视频,拷贝到你的电脑硬盘里。那么数据都是在哪些设备上的呢?键盘、内存、硬盘、外接设备等等。

我们把这种数据的传输,可以看做是一种数据的流动,按照流动的方向,以内存为基准,分为输入input输出output ,即流向内存是输入流,流出内存的输出流。

Java中I/O操作主要是指使用java.io包下的内容,进行输入、输出操作。输入也叫做读取数据,输出也叫做作写出数据。

4.2 IO的分类

根据数据的流向分为:输入流输出流

  • 输入流 :把数据从其他设备上读取到内存中的流。
  • 输出流 :把数据从内存 中写出到其他设备上的流。

根据数据的类型分为:字节流字符流

  • 字节流 :以字节为单位,读写数据的流。
  • 字符流 :以字符为单位,读写数据的流。

1字符=2字节(byte) 1个字节=8个二进制位(bit)

例如 字节->二进制位 ===== 97->0110 0001

此处关于字符占字节的描述不准确,请看这里

4.3 IO的流向说明图解

4.4 顶级父类们

输入流输出流
字节流字节输入流
InputStream
字节输出流
OutputStream
字符流字符输入流
Reader
字符输出流
Writer

第五章 字节流

5.1 一切皆为字节

一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。

任意的文本编辑器(记事本,notepad++)

在打开文件的时候,都会查询编码表,把字节转换为字符表示

0-127:查询ASCII表

其他值:查询系统默认码表(中文系统GBK)

5.2 字节输出流

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

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

写入数据的原理:由内存到硬盘

  • java程序–>jvm(java虚拟机)–>os(操作系统)–>os调用写数据的方法–>把数据写入到文件

字节输出流的使用步骤:

  1. 创建一个FileOutputStream对象,构造方法中传递写入数据的路径
  2. 调用FileOutputStream对象中的方法write方法,把数据写入到文件中
  3. 释放资源(流的使用会占用一定的内存,使用完毕要把内存清空提高程序的效率)

小贴士:

close方法,当完成流的操作时,必须调用此方法,释放系统资源。

5.3 FileOutputStream类

OutputStream有很多子类,我们从最简单的一个子类开始。

java.io.FileOutputStream类是文件输出流,用于将数据写出到文件。

构造方法

  • public FileOutputStream(File file):创建文件输出流以写入由指定的 File对象表示的文件。
  • public FileOutputStream(String name): 创建文件输出流以指定的名称写入文件。

当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。

构造方法的作用:

  1. 创建一个FileOutputStream对象
  2. 根据构造方法中传递的文件路径创建一个空的文件
  3. 会把FileOutputStream对象指向创建好的文件。
  • 构造举例,代码如下:
1
2
3
4
5
6
7
8
9
10
public class FileOutputStreamConstructor throws IOException {
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileOutputStream fos = new FileOutputStream(file);

// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("b.txt");
}
}

写出字节数据

  1. 写出字节write(int b) 方法,每次可以写出一个字节数据,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 写出数据
fos.write(97); // 写出第1个字节
fos.write(98); // 写出第2个字节
fos.write(99); // 写出第3个字节
// 关闭资源
fos.close();
}
}
输出结果:
abc

小贴士:

  1. 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
  2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
  1. 写出字节数组write(byte[] b),每次可以写出数组中的数据,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 字符串转换为字节数组
byte[] b = "黑马程序员".getBytes();
// 写出字节数组数据
fos.write(b);
// 关闭资源
fos.close();
}
}
输出结果:
黑马程序员
  1. 写出指定长度字节数组write(byte[] b, int off, int len) ,每次写出从off索引开始,len个字节,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 字符串转换为字节数组
byte[] b = "abcde".getBytes();
// 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
fos.write(b,2,2);
// 关闭资源
fos.close();
}
}
输出结果:
cd

数据追加续写

经过以上的演示,每次程序运行,创建输出流对象,都会清空目标文件中的数据。如何保留目标文件中数据,还能继续添加新数据呢?

  • public FileOutputStream(File file, boolean append): 创建文件输出流以写入由指定的 File对象表示的文件。
  • public FileOutputStream(String name, boolean append): 创建文件输出流以指定的名称写入文件。

这两个构造方法,参数中都需要传入一个boolean类型的值,true 表示追加数据,false 表示清空原有数据。这样创建的输出流对象,就可以指定是否追加续写了,代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt"true);
// 字符串转换为字节数组
byte[] b = "abcde".getBytes();
// 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
fos.write(b);
// 关闭资源
fos.close();
}
}
文件操作前:cd
文件操作后:cdabcde

写出换行

Windows系统里,换行符号是\r\n

Linux系统里,换行符号是/n

Mac系统,换行是\r

把以指定是否追加续写了,代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 定义字节数组
byte[] words = {97,98,99,100,101};
// 遍历数组
for (int i = 0; i < words.length; i++) {
// 写出一个字节
fos.write(words[i]);
// 写出一个换行, 换行符号转成数组写出
fos.write("\r\n".getBytes());
}
// 关闭资源
fos.close();
}
}

输出结果:
a
b
c
d
e
  • 回车符\r和换行符\n
    • 回车符:回到一行的开头(return)。
    • 换行符:下一行(newline)。
  • 系统中的换行:
    • Windows系统里,每行结尾是 回车+换行 ,即\r\n
    • Unix系统里,每行结尾只有 换行 ,即\n
    • Mac系统里,每行结尾是 回车 ,即\r。从 Mac OS X开始与Linux统一。

5.4 字节输入流

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

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

读取数据的原理:硬盘–>内存

  • java程序–>jvm–>os–>os读取数据的方法–>读取文件

字节输入流的使用步骤:

  1. 创建InputStream对象,构造方法中绑定要读取的数据源
  2. 使用FileInputStream对象中的方法read,读取文件
  3. 释放资源

小贴士:

close方法,当完成流的操作时,必须调用此方法,释放系统资源。

5.5 FileInputStream类

java.io.FileInputStream类是文件输入流,从文件中读取字节。

构造方法

  • FileInputStream(File file): 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
  • FileInputStream(String name): 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。

构造方法的作用:

  1. 创建一个FileInputStream对象
  2. 会把FileInputStream对象指向构造方法中要读取的文件。

当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出FileNotFoundException

  • 构造举例,代码如下:
1
2
3
4
5
6
7
8
9
10
public class FileInputStreamConstructor throws IOException{
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileInputStream fos = new FileInputStream(file);

// 使用文件名称创建流对象
FileInputStream fos = new FileInputStream("b.txt");
}
}

读取字节数据

  1. 读取字节read方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回-1,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class FISRead {
public static void main(String[] args) throws IOException{
// 使用文件名称创建流对象
FileInputStream fis = new FileInputStream("read.txt");
// 读取数据,返回一个字节
int read = fis.read();
System.out.println((char) read);
read = fis.read();
System.out.println((char) read);
read = fis.read();
System.out.println((char) read);
read = fis.read();
System.out.println((char) read);
read = fis.read();
System.out.println((char) read);
// 读取到末尾,返回-1
read = fis.read();
System.out.println( read);
// 关闭资源
fis.close();
}
}
输出结果:
a
b
c
d
e
-1

循环改进读取方式,代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class FISRead {
public static void main(String[] args) throws IOException{
// 使用文件名称创建流对象
FileInputStream fis = new FileInputStream("read.txt");
// 定义变量,保存数据
int b ;
// 循环读取
while ((b = fis.read())!=-1) {
System.out.println((char)b);
}
// 关闭资源
fis.close();
}
}
输出结果:
a
b
c
d
e

小贴士:

  1. 虽然读取了一个字节,但是会自动提升为int类型。
  2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
  1. 使用字节数组读取read(byte[] b),每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回-1 ,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class FISRead {
public static void main(String[] args) throws IOException{
// 使用文件名称创建流对象.
FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
// 定义变量,作为有效个数
int len ;
// 定义字节数组,作为装字节数据的容器
byte[] b = new byte[2];
// 循环读取
while (( len= fis.read(b))!=-1) {
// 每次读取后,把数组变成字符串打印
System.out.println(new String(b));
}
// 关闭资源
fis.close();
}
}

输出结果:
ab
cd
ed

错误数据d,是由于最后一次读取时,只读取一个字节e,数组中,上次读取的数据没有被完全替换,所以要通过len ,获取有效的字节。

这个写入文件的时候,也要通过write(b,0,len);不然可能就会重复了。

就比方说上面的abcde,如果只调用write(b),就会导致输出的内容abcded

代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class FISRead {
public static void main(String[] args) throws IOException{
// 使用文件名称创建流对象.
FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
// 定义变量,作为有效个数
int len ;
// 定义字节数组,作为装字节数据的容器
byte[] b = new byte[2];
// 循环读取
while (( len= fis.read(b))!=-1) {
// 每次读取后,把数组的有效字节部分,变成字符串打印
System.out.println(new String(b,0,len));// len 每次读取的有效字节个数
}
// 关闭资源
fis.close();
}
}

输出结果:
ab
cd
e

小贴士:

使用数组读取,每次读取多个字节,减少了系统间的IO操作次数,从而提高了读写的效率,建议开发中使用。

5.6 字节流练习:图片复制

复制原理图解

案例实现

复制图片文件,代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Copy {
public static void main(String[] args) throws IOException {
// 1.创建流对象
// 1.1 指定数据源
FileInputStream fis = new FileInputStream("D:\\test.jpg");
// 1.2 指定目的地
FileOutputStream fos = new FileOutputStream("test_copy.jpg");

// 2.读写数据
// 2.1 定义数组
byte[] b = new byte[1024];
// 2.2 定义长度
int len;
// 2.3 循环读取
while ((len = fis.read(b))!=-1) {
// 2.4 写出数据
fos.write(b, 0 , len);
}

// 3.关闭资源
fos.close();
fis.close();
}
}

小贴士:

流的关闭原则:先开后关,后开先关。

第六章 字符流

当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。

1个中文

gbk:占用两个字节

utf-8:占用3个字节

而字节流,一次只能读取一个字节

所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。

6.1 字符输入流【Reader】

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

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

字节输入流的使用步骤:

  1. 创建FileReader对象,构造方法中绑定要读取的数据源
  2. 使用FileReader对象中的方法read读取文件
  3. 释放资源

6.2 FileReader类

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

小贴士:

  1. 字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。

idea中UTF-8

  1. 字节缓冲区:一个字节数组,用来临时存储字节数据。

构造方法

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

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

构造方法的作用:

  1. 创建一个FileReader对象
  2. 会把FileReader对象指向要读取的文件
  • 构造举例,代码如下:
1
2
3
4
5
6
7
8
9
10
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");
}
}

读取字符数据

  1. 读取字符read方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1,循环读取,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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),每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1 ,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();
}
}
输出结果:
黑马
程序
员序

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();
}
}

输出结果:
黑马
程序

6.3 字符输出流【Writer】

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

  • void write(int c) 写入单个字符。
  • void write(char[] cbuf)写入字符数组。
  • abstract void write(char[] cbuf, int off, int len)写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
  • void write(String str)写入字符串。
  • void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
  • void flush()刷新该流的缓冲。
  • void close() 关闭此流,但要先刷新它。

字符输出流的使用步骤:

  1. 创建FileWriter对象,构造方法中绑定要写入数据的目的地。
  2. 使用FileWriter中的write方法,把数据写入到内存缓冲区中(字符转换为字节的过程)
  3. 使用FileWriter中的flush,把内存缓冲区中的数据,刷新到文件中
  4. 释放资源(会先把内存缓冲区中的数据刷新到文件中)

6.4 FileWriter类

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

构造方法

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

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

构造方法的作用:

  1. 会创建一个FileWriter对象
  2. 会根据构造方法中传递的文件/文件的路径,创建一个文件
  3. 会把FileWriter对象,指向创建好的文件。
  • 构造举例,代码如下:
1
2
3
4
5
6
7
8
9
10
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");
}
}

基本写出数据

写出字符write(int b) 方法,每次可以写出一个字符数据,代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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方法,数据只是保存到了缓冲区,并未写出到文件中。

关闭和刷新

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

  • flush :刷新缓冲区,流对象可以继续使用。
  • close:先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。

代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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方法,释放系统资源。

写出其他数据

  1. 写出字符数组write(char[] cbuf)write(char[] cbuf, int off, int len) ,每次可以写出字符数组中的数据,用法类似FileOutputStream,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 字符串转换为字节数组
char[] chars = "黑马程序员".toCharArray();

// 写出字符数组
fw.write(chars); // 黑马程序员

// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
fw.write(b,2,2); // 程序

// 关闭资源
fos.close();
}
}
  1. 写出字符串write(String str)write(String str, int off, int len) ,每次可以写出字符串中的数据,更为方便,代码使用演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 字符串
String msg = "黑马程序员";

// 写出字符数组
fw.write(msg); //黑马程序员

// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
fw.write(msg,2,2); // 程序

// 关闭资源
fos.close();
}
}
  1. 续写和换行:操作类似于FileOutputStream。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象,可以续写数据
FileWriter fw = new FileWriter("fw.txt"true);
// 写出字符串
fw.write("黑马");
// 写出换行
fw.write("\r\n");
// 写出字符串
fw.write("程序员");
// 关闭资源
fw.close();
}
}
输出结果:
黑马
程序员

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

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

第七章 IO异常的处理

7.1 JDK7前处理

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class HandleException1 {
public static void main(String[] args) {
// 声明变量
FileWriter fw = null;
try {
//创建流对象
fw = new FileWriter("fw.txt");
// 写出数据
fw.write("黑马程序员"); //黑马程序员
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

7.2 JDK7的处理(扩展知识点了解内容)

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

格式:

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

代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Demo02TryCatch {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("c:\\users\\kitchen\\desktop\\abc\\abc.txt");
FileOutputStream fos = new FileOutputStream("src\\demo35\\abc.txt")) {
int len=0;
while((len=fis.read())!=-1) {
fos.write(len);
}
} catch (IOException e) {
System.out.println(e);
}
}
}

7.3 JDK9的改进(扩展知识点了解内容)

JDK9中try-with-resource 的改进,对于引入对象的方式,支持的更加简洁。被引入的对象,同样可以自动关闭,无需手动close,我们来了解一下格式。

改进前格式:

1
2
3
4
5
6
7
8
9
// 被final修饰的对象
final Resource resource1 = new Resource("resource1");
// 普通对象
Resource resource2 = new Resource("resource2");
// 引入方式:创建新的变量保存
try (Resource r1 = resource1;
Resource r2 = resource2) {
// 使用对象
}

改进后格式:

1
2
3
4
5
6
7
8
9
// 被final修饰的对象
final Resource resource1 = new Resource("resource1");
// 普通对象
Resource resource2 = new Resource("resource2");

// 引入方式:直接引入
try (resource1; resource2) {
// 使用对象
}

改进后,代码使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class TryDemo {
public static void main(String[] args) throws IOException {
// 创建流对象
final FileReader fr = new FileReader("in.txt");
FileWriter fw = new FileWriter("out.txt");
// 引入到try中
try (fr; fw) {
// 定义变量
int b;
// 读取数据
while ((b = fr.read())!=-1) {
// 写出数据
fw.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

第八章 属性集

8.1 概述

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

8.2 Properties类

构造方法

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

基本的存储方法

  • public Object setProperty(String key, String value) : 保存一对属性。
  • public String getProperty(String key) :使用此属性列表中指定的键搜索属性值。
  • public Set<String> stringPropertyNames() :所有键的名称的集合。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

与流相关的方法

store方法

  • public void store(OutputStream out, String comments):将此 Properties 表中的属性列表(键和元素对)写入输出流
  • public void store(Writer writer, String comments):将此 Properties 表中的属性列表(键和元素对)写入输出字符。

注意事项:

  • OutputStream out:字节输出流,不能写入中文

  • Writer writer:字符输出流,可以写中文

  • String comments:注释,用来解释说明保存的文件是做什么的。不能使用中文,会产生乱码,默认是Unicode编码,一般是用””空字符串。

使用步骤:

  1. 创建Properties集合,添加数据
  2. 创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
  3. 使用Properties集合中的方法store,将集合中的临时数据,持久化写入到硬盘中存储
  4. 释放资源

案例演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void show02() {
Properties prop=new Properties();
prop.setProperty("filename", "abc.txt");
prop.setProperty("length","12345");
String str="C:\\Users\\kitchen\\Desktop\\abc";
prop.setProperty("location", str);

try(FileWriter fw=new FileWriter("c:\\users\\kitchen\\desktop\\abc\\abc.txt");) {
prop.store(fw, "save data");
} catch (IOException e) {
e.printStackTrace();
}
}

load方法

  • public void load(InputStream inStream): 从字节输入流中读取键值对。
  • public void load(Reader reader):按简单的面向行的格式从输入字符流中读取键值对

参数:

  • InputStream inStream:字节输入流,不能读取含有中文的键值对
  • Reader reader:字符输入流,能读取含有中文的键值对

使用步骤:

  1. 创建Properties集合对象
  2. 使用Properties集合对象中的方法load读取保存键值对的文件
  3. 遍历Properties集合

注意:

  1. 存储键值对的文件中,键与值默认的连接符号,可以使用等号或者是空格或其他符号
  2. 存储键值对的文件中,可以使用#进行注释,被注释的键值对,不会再被读取
  3. 存储键值对的文件中,键与值默认都是字符串,不用再加引号。

案例演示:

1
2
3
4
5
6
7
8
9
10
11
public static void show03() {
Properties prop=new Properties();
try(FileReader fw=new FileReader("C:\\users\\kitchen\\desktop\\abc\\abc.txt")){
prop.load(fw);
for(String s:prop.stringPropertyNames()) {
System.out.println(s+"="+prop.getProperty(s));
}
}catch (Exception e) {
e.printStackTrace();
}
}
发布:2019-12-10 19:46:06
修改:2020-07-11 12:15:54
链接:https://meethigher.top/blog/2019/file-and-io-stream/
标签:java 
付款码 打赏 分享
shift+ctrl+1可控制目录显示