File类的使用

File类的实例化

  • java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关

  • File 能新建、删除、重命名文件和目录,但File 不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。

  • 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。

  • File对象可以作为参数传递给流的构造器

  • File类提供了以下四种构造器,这里只说前三种

构造器 描述
File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 File实例。
File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的 File实例。
File(URI uri) 通过将给定的 file: URI转换为抽象路径名来创建新的 File实例。

首先,在当前目录下新建如下目录,并在hello.txt中写入hello

  • IO
    • IOTest
      • hello.txt

在D盘根目录下新建如下目录,并在world.txt中写入world

  • IO
    • IOTest
      • world.txt

下面演示三种构造器的使用

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
@Test
public void test1(){
File file1 = new File("IO", "IOTest");
File file2 = new File("IO");
File file3 = new File(file1, "hello.txt");

System.out.println(file1);
System.out.println(file2);
System.out.println(file3);

System.out.println("****************");
File file4 = new File("D:\\IO", "IOTest");
File file5 = new File("D:\\IO");
File file6 = new File(file4, "world.txt");
System.out.println(file4);
System.out.println(file5);
System.out.println(file6);
/*
IO\IOTest
IO
IO\IOTest\hello.txt
****************
D:\IO\IOTest
D:\IO
D:\IO\IOTest\world.txt
*/
}

File类的常用方法1

变量和类型 方法 描述
String getAbsolutePath() 返回此抽象路径名的绝对路径名字符串。
String getPath() 将此抽象路径名转换为路径名字符串。
String getName() 返回此抽象路径名表示的文件或目录的名称。
String getParent() 返回此抽象路径名父项的路径名字符串,如果此路径名未指定父目录,则返回 null
long length() 返回此抽象路径名表示的文件的长度。
long lastModified() 返回上次修改此抽象路径名表示的文件的时间。(毫秒值)
String[] list() 返回一个字符串数组,用于命名此抽象路径名表示的目录中的文件和目录。
File[] listFiles() 返回一个抽象路径名数组,表示此抽象路径名表示的目录中的文件。
boolean renameTo(File dest) 重命名此抽象路径名表示的文件。
  • 下面来对这些方法进行测试
  • public String getAbsolutePath():获取绝对路径
  • public String getPath() :获取路径
  • public String getName() :获取名称
  • public String getParent():获取上层文件目录路径。若无,返回null
  • public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
  • public long lastModified() :获取最后一次的修改时间,毫秒值(把它扔进Date里就能看懂具体时间了)
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
34
35
@Test
public void test2() {
File file1 = new File("IO\\IOTest\\hello.txt");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
System.out.println(file1.getName());
System.out.println(file1.getParentFile());
System.out.println(file1.length());
System.out.println(new Date(file1.lastModified()));

System.out.println("*************************");

File file2 = new File("D:\\IO\\IOTest\\world.txt");
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getPath());
System.out.println(file2.getName());
System.out.println(file2.getParentFile());
System.out.println(file2.length());
System.out.println(new Date(file2.lastModified()));
/*
D:\内卷!启动\Java高级\Java---IO流\IO\IOTest\hello.txt
IO\IOTest\hello.txt
hello.txt
IO\IOTest
5
Tue Apr 26 16:07:20 CST 2022
*************************
D:\IO\IOTest\world.txt
D:\IO\IOTest\world.txt
world.txt
D:\IO\IOTest
5
Tue Apr 26 15:12:26 CST 2022
*/
}

如下的两个方法适用于文件目录:
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的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
29
30
31
@Test
public void test3() {
//文件需存在!!!
File file = new File("D:\\Chrome下载\\计算机网络 期末不挂科");
String[] strings = file.list();
for (String s : strings) {
System.out.println(s);
}
System.out.println("**************");
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);
}
}
/*
第一章 概述
第七章 总结
第三章 数据链路层
第二章 物理层
第五章 传输层
第六章 应用层
第四章 网络层
**************
D:\Chrome下载\计算机网络 期末不挂科\第一章 概述
D:\Chrome下载\计算机网络 期末不挂科\第七章 总结
D:\Chrome下载\计算机网络 期末不挂科\第三章 数据链路层
D:\Chrome下载\计算机网络 期末不挂科\第二章 物理层
D:\Chrome下载\计算机网络 期末不挂科\第五章 传输层
D:\Chrome下载\计算机网络 期末不挂科\第六章 应用层
D:\Chrome下载\计算机网络 期末不挂科\第四章 网络层
*/

以file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
执行完这个操作之后我们的hello.txt就被移到了D:\IO\IOTest目录下,且被重命名为了helloworld.txt,但其中输入的hello不会改变

1
2
3
4
5
@Test
public void test4() {
File file = new File("IO\\IOTest\\hello.txt");
file.renameTo(new File("D:\\IO\\IOTest\\helloworld.txt"));
}

File类的常用方法2

变量和类型 方法 描述
boolean isDirectory() 测试此抽象路径名表示的文件是否为目录。
boolean isFile() 测试此抽象路径名表示的文件是否为普通文件。
boolean exists() 测试此抽象路径名表示的文件或目录是否存在。
boolean canRead() 测试应用程序是否可以读取此抽象路径名表示的文件。
boolean canWrite() 测试应用程序是否可以修改此抽象路径名表示的文件。
boolean isHidden() 测试此抽象路径名指定的文件是否为隐藏文件。
boolean createNewFile() 当且仅当具有此名称的文件尚不存在时,以原子方式创建由此抽象路径名命名的新空文件。
boolean mkdir() 创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
boolean mkdirs() 创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建
boolean delete() 删除此抽象路径名表示的文件或目录。要想删除成功,文件目录下不能有子目录或文件

连续执行两次此方法,就不用手动删除了[doge]

1
2
3
4
5
6
7
8
9
10
11
@Test
public void test5() throws IOException {
File file = new File("hi.txt");
if(!file.exists()){
file.createNewFile();
System.out.println("创建成功");
}else {
file.delete();
System.out.println("删除成功");
}
}
  • public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false

  • public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。

  • public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建

  • public boolean delete():删除文件或者文件夹。

  • 删除注意事项:Java中的删除不走回收站。

猜一猜下面的代码会输出什么? 创建成功2 删除失败

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void test6() throws IOException {
File file = new File("Steam\\games\\Apex");
//file.createNewFile(); //报错 系统找不到指定的路径
boolean mkdir = file.mkdir();
if (mkdir) System.out.println("创建成功1");
boolean mkdirs = file.mkdirs();
if (mkdirs) System.out.println("创建成功2");
file = new File("Steam");
boolean IsDelete = file.delete();
if(IsDelete) System.out.println("删除成功");
else System.out.println("删除失败");
}
  • public boolean isDirectory():判断是否是文件目录
  • public boolean isFile() :判断是否是文件
  • public boolean exists() :判断是否存在
  • public boolean canRead() :判断是否可读
  • public boolean canWrite() :判断是否可写
  • public boolean isHidden() :判断是否隐藏
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void test7() {
File file = new File("D:\\IO\\IOTest\\world.txt");
System.out.println("目录?"+file.isDirectory());
System.out.println("普通文件?"+file.isFile());
System.out.println("存在?"+file.exists());
System.out.println("能读?"+file.canRead());
System.out.println("能写?"+file.canWrite());
System.out.println("隐藏?"+file.isHidden());

System.out.println("*******************");
file=file.getParentFile();
System.out.println("目录?"+file.isDirectory());
System.out.println("普通文件?"+file.isFile());
System.out.println("存在?"+file.exists());
System.out.println("能读?"+file.canRead());
System.out.println("能写?"+file.canWrite());
System.out.println("隐藏?"+file.isHidden());
}

练习

  • 判断指定目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
1
2
3
4
5
6
7
File file = new File("XXX");
if(file.exists()){
for (String s : file.list()) {
if (s.endsWith(".jpg"))
System.out.println(s);
}
}
1
2
3
4
5
6
7
File file = new File("XXX");
if (file.exists()) {
for (File listFile : file.listFiles()) {
if (listFile.getName().endsWith(".jpg"))
System.out.println(listFile);
}
}
1
2
3
4
5
6
7
8
9
10
11
File file = new File("XXX");
if (file.exists()) {
for (File listFile : file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".jpg");
}
})) {
System.out.println(listFile);
}
}
  • 遍历指定目录所有文件名称,包括子文件目录中的文件。
    • 拓展1:并计算指定目录占用空间的大小
    • 拓展2:删除指定文件目录及其下的所有文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
public void test9(){
printAllSubFile(new File("YOUR\\FILE"));
}

public void printAllSubFile(File file){
if(file.exists()){
File[] files = file.listFiles();
for (File f : files) {
if(f.isFile())
System.out.println(f.getAbsolutePath());
else printAllSubFile(f);
}
}else System.out.println("文件不存在");
}
1
2
3
4
5
6
7
8
9
10
11
public long getDirectorySize(File file) {
long size = 0L;
if (file.exists()) {
for (File f : file.listFiles()) {
if (f.isFile()) {
size += f.length();
} else getDirectorySize(f);
}
} else System.out.println("文件不存在");
return size;
}

注意测试的时候不要拿重要文件去测试,删除了之后不会放到回收站!!

1
2
3
4
5
6
7
8
public void deleteDirectory(File file) {
for (File f : file.listFiles()) {
if (f.isFile())
f.delete();
else deleteDirectory(f);
}
file.delete();
}

IO流原理及流的分类

IO流原理

  • I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。

  • Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行。

  • java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。

  • 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。

  • 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。

所谓的输入和输出,我们都是站在程序(内存)的角度来说的

流的分类

  • 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)

  • 按数据流的流向不同分为:输入流,输出流

  • 按流的角色的不同分为:节点流,处理流

抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
InputStream FileInputStream (read(byte[] buffer))
OutputStream FileOutputStream (write(byte[] buffer,0,len)
Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush()
  • Java的IO流共涉及40多个类,实际上非常规则,都是从上述4个抽象基类派生的。

  • 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

IO流体系

分类 字节输入流 字节输出流 字符输入流 字符输出流
抽象基类 InputStream OutputStream Reader Writer
访问文件 FilelnputStream FileOutputStream FileReader FileWriter
访问数组 ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
访问管道 PipedInputStream PipedOutputStream PipedReader PipedWriter
访问字符串 StringReader StringWriter
缓冲流 BufferedInputStream BufferedOuputStream BufferedReader BufferedWriter
转换流 InputStreamReader OutputStreamWriter
对象流 ObjectInputStream ObjectOutputStream
FilterlnputStream FilterOutputStream FilterReader FilterWriter
打印流 PrintStream PrintWriter
推回输入流 PushbacklnputStream PushbackReader
特殊流 DatalnputStream DataOutputStream

节点流(或文件流)

FileReader读入数据的基本操作

  • 在当前module下新建一个hello.txt文件,随便写点东西进去。

  • 读取文件四个步骤

  1. 实例化File对象,指明要操作的文件

  2. 提供具体的流

  3. 数据的读入过程

  4. 流的关闭操作

后面的文件操作大体也都是这四个步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
public void test1() {
FileReader fr = null;
try {
File file = new File("hello.txt");
fr = new FileReader(file);
int a;
while ((a = fr.read()) != -1)
System.out.print((char) a);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1

  2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理

  3. 读入的文件一定要存在,否则就会报FileNotFoundException。

看似代码乱七八糟没有规律,其实核心代码就下面这几行

1
2
3
4
5
6
File file = new File("hello.txt");      //1. 实例化File对象
FileReader fr = new FileReader(file); //2. 提供具体的流
int a;
while ((a = fr.read()) != -1) //3. 数据的读入操作
System.out.print((char) a);
fr.close(); //4. 流的关闭操作

除了最后一步关闭流的操作,选中剩下的代码,IDEA中按住CTRL+ALT+T,用try/catch/finally将代码包起来,然后将最后的fr.closs()操作扔进finally里,判断一下fr!=null然后在关闭,就大功告成了。

此次代码测试是在测试方法中执行的,hello.txt文件路径是相较于当前Module下的,如果你在Main方法中进行测试,请在当前工程下新建hello.txt文件

使用read(char[] cbuf)读入数据

变量和类型 方法 描述
int read() 读一个字符。
int read(char[] cbuf, int offset, int length) 将字符读入数组的一部分。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
public void test2() {
FileReader fr = null;
try {
File file = new File("hello.txt");
char[] cbuf = new char[5];
fr = new FileReader(file);
int len;
while ((len = fr.read(cbuf)) != -1) {
System.out.print(new String(cbuf, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

其中while循环可以改写成下面这样

1
2
3
4
5
while ((len = fr.read(cbuf)) != -1) {
for (int i = 0; i < len; i++) {
System.out.println(cbuf[i]);
}
}

注意:for循环中的条件是i < len千万不能写成i < cbuf.length

1
2
3
4
5
6
7
8
9
10
//错法一
while ((len = fr.read(cbuf)) != -1) {
for (int i = 0; i < cbuf.length; i++) {
System.out.print(cbuf[i]);
}
}
//另一种错法,跟上面的错法,异曲同工
while ((len = fr.read(cbuf)) != -1) {
System.out.print(new String(cbuf));
}
1
2
3
4
5
6
7
8
9
10
11
@Test
public void test2() {
File file = new File("hello.txt"); //1. 实例化File对象
FileReader fr = new FileReader(file); //2. 提供具体的流
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) { //3. 数据的读入操作
System.out.println(new String(cbuf, 0, len));
}
fr.close(); //4. 流的关闭操作
}

FileWriter写出数据的操作

从内存中写出数据到硬盘的文件里。

输出操作,对应的File可以不存在的。并不会报异常

  • File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。

  • File对应的硬盘中的文件如果存在:

    • 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖

    • 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容

  • 写出数据四个步骤

  1. 实例化File对象,指明要操作的文件

  2. 提供具体的流

  3. 数据的写出过程

  4. 流的关闭操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void test3() {
FileWriter fw = null;
try {
File file = new File("hello.txt");
fw = new FileWriter(file,true);
fw.write("随便写点什么东西");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
@Test
public void test3() {
File file = new File("hello.txt"); //1. 实例化File对象,指明要操作的文件
FileWriter fw = new FileWriter(file, true); //2. 提供具体的流
fw.write("随便写点什么.."); //3. 数据的写出过程
fw.close(); //4. 流的关闭操作
}

使用FileReader和FileWriter实现文本文件的复制

将刚刚学的两个方法合体,就能完成对文本文件的复制啦

如果想对非文本文件进行复制(.jpg, .png, .avi, .mp4等),则需要用待会儿说的字节流.

下面我们将hello.txt,复制到同目录下的hello1.txt中

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
34
@Test
public void test4() {
FileReader fr = null;
FileWriter fw = null;
try {
File origin = new File("hello.txt");
File dest = new File("hello1.txt");
fr = new FileReader(origin);
fw = new FileWriter(dest);

char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void test4() {
File origin = new File("hello.txt"); //创建需要被复制的文件的对象
File dest = new File("hello1.txt"); //创建目标文件对象
FileReader fr = new FileReader(origin); //提供读入流
FileWriter fw = new FileWriter(dest); //提供写出流
char[] cbuf = new char[5]; //记录每次读入到cbuf数组中的字符的个数
int len;
while ((len = fr.read(cbuf)) != -1) { //执行读入操作
fw.write(cbuf, 0, len); //执行写出操作,每次写出len个字符
}
fr.close(); //流的关闭
fw.close(); //流的关闭
}

使用FileInputStream不能读取文本文件的测试

测试FileInputStream和FileOutputStream的使用

使用方法与上面的字符流几乎一样

如果你的hello.txt中,存在中文,那大概率是会出现乱码的。以UTF-8为例,一个中文汉字占用3个字节。然而下面的代码,我设置的每次读入5个字节。例如hello.txt中只存放 “哈喽” 两个字,这两个字一共占6个字节,那么"喽"这个字会被分成两半读入,输出的时候自然就是乱码了,但是"哈"还是会正常输出的。除非你把byte数组开的超级大,一次性将所有字节全部读入(不会真的有人这么做吧)

虽说不能读取,但是还是可以完成复制操作的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
public void test5() {
FileInputStream fis = null;
try {
File file = new File("hello.txt");
fis = new FileInputStream(file);
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
@Test
public void test5(){
File file = new File("hello.txt"); //创建File对象
FileInputStream fis = new FileInputStream(file); //提供具体的流
byte[] buffer = new byte[5]; //每次读取5个字节
int len;
while ((len=fis.read(buffer))!=-1){ //执行读入操作
System.out.println(new String(buffer,0,len)); //每次写出len个字节
}
fis.close(); //流的关闭
}

结论:

  1. 对于文本文件(.txt, .java, .c, .cpp)的读取,使用字符流处理

  2. 对于非文本文件(.jpg, .mp3, .mp4, .avi, .doc, .ppt,…),使用字节流处理

用FileInputStream和FileOutputStream复制文件的方法测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void test6() {
File origin = new File("hello.txt"); //创建被复制文件的对象
File dest = new File("hello2.txt"); //创建写出目标文件对象
FileInputStream fis = new FileInputStream(origin); //提供读入流
FileOutputStream fos = new FileOutputStream(dest); //提供写出流
byte[] buffer = new byte[5]; //记录每次读入到buffer数组中的字节的个数
int len;
while ((len = fis.read(buffer)) != -1) { //执行读入操作
fos.write(buffer, 0, len); //执行写出操作,每次写出len个字符
}
fis.close(); //流的关闭操作
fos.close(); //流的关闭操作
}

将核心代码改写成一个方法,我们就可以对指定文件进行复制了

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 void copyFile(String originPath, String destPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File origin = new File(originPath);
File dest = new File(destPath);
fis = new FileInputStream(origin);
fos = new FileOutputStream(dest);
byte[] buffer = new byte[1024 * 10];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
@Test
public void copyFileTest() {
long start = System.currentTimeMillis();
copyFile("D:\\Chrome下载\\计算机网络 期末不挂科\\第一章 概述\\计算机网络体系结构.mp4", "D:\\Chrome下载\\计算机网络 期末不挂科\\第一章 概述\\计算机网络体系结构1.mp4");
long end = System.currentTimeMillis();
System.out.println("复制完成,耗时" + (end - start) + "毫秒");
}

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

1
2
3
4
5
6
7
8
9
10
11
public void copyFileWithBuffer(String oriPath,String destPath){
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(oriPath));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
byte[] buffer = new byte[1024];
int len;
while ((len=bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
bis.close();
bos.close();
}
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
public void copyFileWithBuffer(String oriPath,String destPath){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(oriPath));
bos = new BufferedOutputStream(new FileOutputStream(destPath));
byte[] buffer = new byte[1024];
int len;
while ((len=bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos!=null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

实现图片加密操作

我们读取byte时,进行异或操作,再将其写入到test中。
如果我们需要解密,那么再次对同一个数进行异或操作即可。

A对B进行两次异或操作结果不变,即A ^ B ^ B = A
我们在加密的时候进行了第一次异或,那我们解密的时候进行第二次异或就好啦

1
2
3
4
5
6
7
8
9
10
11
12
public void test2() {
FileInputStream fis = new FileInputStream("C:\\Users\\15863\\Desktop\\Picture\\test.png");
FileOutputStream fos = new FileOutputStream("C:\\Users\\15863\\Desktop\\Picture\\test1.png");
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
for (int i = 0; i < len; i++) buffer[i] ^= 5;
fos.write(buffer);
}
fis.close();
fos.close();
}

转换流

转换流概述与InputStreamReader的使用

转换流提供了在字节流和字符流之间的转换
Java API提供了两个转换流:

  • InputStreamReader:将InputStream转换为Reader
    • 实现将字节的输入流按指定字符集转换为字符的输入流。
    • 需要和InputStream“套接”。
    • 构造器
      • public InputStreamReader(InputStreamin)
      • public InputSreamReader(InputStreamin,StringcharsetName)
      • 如:Reader isr= new InputStreamReader(System.in,”gbk”);
  • OutputStreamWriter:将Writer转换为OutputStream
    • 实现将字符的输出流按指定字符集转换为字节的输出流。
    • 需要和OutputStream“套接”。
    • 构造器
      • public OutputStreamWriter(OutputStreamout)
      • public OutputSreamWriter(OutputStreamout,StringcharsetName)

字节流中的数据都是字符时,转成字符流操作更高效。

很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

1
2
3
4
5
6
7
8
9
10
11
@Test
public void test3() {
FileInputStream fis = new FileInputStream("hello.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
char[] c = new char[1024];
int len;
while ((len = isr.read(c)) != -1) {
System.out.println(new String(c, 0, len));
}
isr.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
public void test3() {
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("hello.txt");
isr = new InputStreamReader(fis, "UTF-8");
char[] c = new char[1024];
int len;
while ((len = isr.read(c)) != -1) {
System.out.println(new String(c, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

转换流实现将utf-8文件转换成gbk文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void test4() {
File file1 = new File("hello.txt");
File file2 = new File("hello_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
char[] chars = new char[1024];
int len;
while ((len = isr.read()) != -1) {
osw.write(chars, 0, len);
}
isr.close();
osw.close();
}

打开我们刚生成的hello_gbk.txt文件,IDEA会提示该文件以错误的编码加载:“UTF-8”,以‘GBK’重新加载之后即可正常显示。那我们就成功地将utf-8文件转换成了gbk文件

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
34
35
@Test
public void test4() {
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
File file1 = new File("hello.txt");
File file2 = new File("hello_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
isr = new InputStreamReader(fis, "utf-8");
osw = new OutputStreamWriter(fos, "gbk");
char[] chars = new char[20];
int len;
while ((len = isr.read(chars)) != -1) {
osw.write(chars, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

标准的输入流、输出流

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

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

System.in的类型是InputStream

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

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

  • public static void setIn(InputStreamin)
  • public static void setOut(PrintStreamout)

练习

Create a program named MyInput.java: Contain the methods for reading int,double, float, boolean, short, byte and String values from the keyboard.

相当于自己写一个Scanner方法,实现nextInt(),nextLong()等方法,我们可以通过读取字符串,间接的把它转化成我们需要的数据类型

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
34
35
36
public class MyInput {
public static String readString() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}

public static int readInt() {
return Integer.parseInt(readString());
}

public static Long readLong() {
return Long.parseLong(readString());
}

public static short readShort() {
return Short.parseShort(readString());
}

public static byte readByte() {
return Byte.parseByte(readString());
}

public static Float readFloat() {
return Float.parseFloat(readString());
}

public static Double readDouble() {
return Double.parseDouble(readString());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) {
System.out.println("输入int类型");
int a = MyInput.readInt();
System.out.println(a);
System.out.println("输入double类型");
double b = MyInput.readDouble();
System.out.println(b);
System.out.println("输入float类型");
float c = MyInput.readFloat();
System.out.println(c);
System.out.println("输入byte类型");
byte d = MyInput.readByte();
System.out.println(d);
System.out.println("输入String类型");
String str = MyInput.readString();
System.out.println(str);
System.out.println("输入Long类型");
long e = MyInput.readLong();
System.out.println(e);
System.out.println("输入Short类型");
Short f = MyInput.readShort();
System.out.println(f);
}

打印流

实现将基本数据类型的数据格式转化为字符串输出

打印流:PrintStream和PrintWriter

  • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
  • PrintStream和PrintWriter的输出不会抛出IOException异常
  • PrintStream和PrintWriter有自动flush功能
  • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用PrintWriter 类。
  • System.out返回的是PrintStream的实例
1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void test1() {
try (PrintStream ps = new PrintStream("test.txt")) {
System.setOut(ps); // 把标准输出流(控制台输出)改成文件
for (int i = 0; i <= 255; i++) {
System.out.print((char) i);
if (i % 40 == 0) System.out.println(); //40个换一行
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

数据流

为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。

数据流有两个类:(用于读取和写出基本数据类型、String类的数据)

  • DataInputStream和DataOutputStream
  • 分别“套接”在InputStream和OutputStream子类的流上
    DataInputStream中的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
public void test2() {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeBoolean(true);
dos.flush();
dos.writeUTF("张三");
dos.flush();
dos.writeInt(18);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
public void test3() {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("data.txt"));
boolean isMale = dis.readBoolean();
String name = dis.readUTF();
int age = dis.readInt();
System.out.println("name = " + name);
System.out.println("age = " + age);
System.out.println("isMale = " + isMale);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

对象流

对象序列化机制的理解

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void test4() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject("敌方小队全灭,你是新的击杀王");
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

查看String的源码,发现String已经继承了java.io.Serializable,所以String是可序列化的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
public void test5() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
System.out.println((String) obj);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

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

若某个类实现了Serializable接口,该类的对象就是可序列化的:

  • 创建一个ObjectOutputStream
  • 调用ObjectOutputStream对象的writeObject(对象) 方法输出可序列化对象
  • 注意写出一次,操作flush()一次

反序列化

  • 创建一个ObjectInputStream对象调用readObject() 方法读取流中的对象

注意:如果某个类的属性不是基本数据类型或String 类型,而是另一个引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的Field 的类也不能序列化

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
34
35
36
import java.io.Serializable;

public class Person implements Serializable {
public static final long serialVersionUID = 16513654L;
private String name;
private int age;

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void test1() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new Person("张三", 18));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
public void test2() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object o = ois.readObject();
Person p = (Person) o;
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

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

  1. 需要实现接口:Serializable
  2. 当前类提供一个全局常量:serialVersionUID
  3. 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性,也必须是可序列化的。(默认情况下,基本数据类型可序列化)

注意:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

serialVersionUID的理解

凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:

  • private static final long serialVersionUID;
  • serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
  • 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID可能发生变化。故建议,显式声明。

简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidCastException)

随机存储文件流

RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。

RandomAccessFile 类支持“随机访问” 的方式,程序可以直接跳到文件的任意地方来读、写文件

  • 支持只访问文件的部分内容
  • 可以向已存在的文件后追加内容

RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile类对象可以自由移动记录指针:

  • long getFilePointer():获取文件记录指针的当前位置
  • void seek(long pos):将文件记录指针定位到pos位置

构造器

  • public RandomAccessFile(Filefile, Stringmode)
  • public RandomAccessFile(Stringname, Stringmode)

创建RandomAccessFile类实例需要指定一个mode 参数,该参数指定RandomAccessFile的访问模式:

  • r: 以只读方式打开
  • rw:打开以便读取和写入
  • rwd:打开以便读取和写入;同步文件内容的更新
  • rws:打开以便读取和写入;同步文件内容和元数据的更新

如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。

RandomAccessFile实现数据的读写操作

实现对hello.txt的复制

hello.txt设置为只读模式,hello_raf.txt设置成读写模式,那我们就可以将hello.txt中的内容读入到内存,并写出到hello_raf.txt

此时我们的hello_raf.txt文件并没有创建,但由于我们设置成rw模式,所以当文件不存在时,会自动创建文件,如果文件已经存在,那我们此次操作将会覆盖掉等长的写入内容

举例:如果A文件中已经存在"123321ABC",那我们向A中写入!@#,那A最终的结果是"!@#321ABC"。

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
@Test
public void test() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile("hello.txt", "r");
raf2 = new RandomAccessFile("hello_raf.txt", "rw");
byte[] buffer = new byte[1024];
int len;
while ((len = raf1.read(buffer)) != -1)
raf2.write(buffer, 0, len);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf1 != null) {
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (raf2 != null) {
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

RandomAccessFile实现数据的插入操作

RandomAccessFile中提供了一个方法

void seek(long pos) 设置从此文件的开头开始测量的文件指针偏移量,在该位置进行下一次读取或写入操作。

相当于我们可以指定一下打字光标的位置,如果我们想在文件末尾插入数据,那我们可以将光标位置放到文件末尾
那么具体的操作如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void test2() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("hello.txt", "rw");
raf.seek(new File("hello.txt").length());
raf.write("瓦尔基里准备就绪,随时可以起飞".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

如果我们想在中间插入数据的话,也不能直接插入,直接插入的话,仍然会把光标后面的数据覆盖掉。所以我们要先把光标后面的数据先储存起来,等我们插入完数据之后,再把刚刚储存的数据插入到末尾即可

1
2
3
4
@Test
public void test3() {
insertData(new File("hello.txt"), 7, "我是布洛特亨德尔");
}

这里我图方便,把它封装成了一个方法,具体思路就是先把光标放到我们要插入的地方,然后拿个StringBuilder把光标后面的数据都存起来。然后重置我们的光标到要插入的地方,把要插入的str写入,然后再把StringBuilder保存的数据写入。

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
public void insertData(File file, int index, String str) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(index);
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[1024];
int len;
while ((len = raf.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
raf.seek(index);
raf.write(str.getBytes());
raf.write(sb.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}