Java IO流

File类的使用

前言

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

File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。

后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的目标文件。

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

File类的实例化

常用的构造器有:

  • public File(String pathname)
    • pathname可以是绝对路径或者相对路径。
    • 绝对路径:是一个固定的路径,从盘符开始。
    • 相对路径:是相对于某个位置开始。
  • public File(String parent, String child)
    • 以parent为父路径,child为子路径创建File对象。
  • public File(File parent, String child)
    • 根据一个父File对象和子文件路径创建File对象。
1
2
3
4
5
6
7
8
9
10
@Test
public void test(){
// 相对路径
File file1 = new File("hello.txt");
// 绝对路径
File file2 = new File("E:\\io\\hello.txt");

File file3 = new File("E:\\io", "hello.txt");
File file4 = new File(file3.getParent(), "hello.txt");
}

说明:
IDEA中:

  • 如果大家开发使用JUnit中的单元测试方法测试,相对路径即为当前Module下。

  • 如果大家使用main()测试,相对路径即为当前的Project下。

Eclipse中:不管使用单元测试方法还是使用main()测试,相对路径都是当前的Project下。

路径分隔符:

  • 路径中的每级目录之间用一个路径分隔符隔开。

  • 路径分隔符和系统有关:

    • windows和DOS系统默认使用\来表示
    • UNIX和URL使用/来表示
  • Java程序支持跨平台运行,为了解决这个隐患,File类提供了一个常量:

    • public static final String separator 根据操作系统,动态的提供分隔符。
1
File file = new File("E:" + File.separator + "io" + File.separator + "hello.txt");

File类常用方法

获取功能的方法:

  • public String getAbsolutePath():获取绝对路径
  • public String getPath() :获取路径
  • public String getName() :获取名称
  • public String getParent():获取上层文件目录路径。若无,返回null
  • public long length() :获取文件长度(字节数),不能获取目录的长度
  • public long lastModified() :获取最后一次的修改时间,毫秒值
  • public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
  • public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组

重命名功能的方法:

  • public boolean renameTo(File dest):把文件重命名为指定的文件路径

判断功能的方法:

  • public boolean isDirectory():判断是否是文件目录
  • public boolean isFile() :判断是否是文件
  • public boolean exists() :判断是否存在
  • public boolean canRead() :判断是否可读
  • public boolean canWrite() :判断是否可写
  • public boolean isHidden() :判断是否隐藏

创建功能的方法:

  • public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
  • public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。
    • 注意:如果此文件目录的上层目录不存在,也不创建。
  • public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建。

删除功能的方法:

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

注意:要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录。

练习题:

  • 遍历指定目录所有文件名称,包括子文件目录中的文件。
  • 计算指定目录占用空间的大。
  • 删除指定文件目录及其下的所有文件。

思路:递归

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class ListFilesTest {

public static void main(String[] args) {

// 1.创建目录对象
File dir = new File("E:\\io");

// 2.打印目录的子文件
printSubFile(dir);

// 3.计算指定目录占用空间的大小
long size = getDirectorySize(dir);
System.out.println(size);

// 4.删除指定文件目录及其下的所有文件
deleteDirectory(dir);
}

public static void printSubFile(File dir) {
// 打印目录的子文件
File[] subfiles = dir.listFiles();

for (File f : subfiles) {
if (f.isDirectory()) {// 文件目录
printSubFile(f);
} else {// 文件
System.out.println(f.getAbsolutePath());
}

}
}

public static long getDirectorySize(File file) {
// file是文件,那么直接返回file.length()
// file是目录,把它的下一级的所有大小加起来就是它的总大小
long size = 0;
if (file.isFile()) {
size += file.length();
} else {
File[] all = file.listFiles();// 获取file的下一级
// 累加all[i]的大小
for (File f : all) {
size += getDirectorySize(f);// f的大小;
}
}
return size;
}

public static void deleteDirectory(File file) {
// 如果file是文件,直接delete
// 如果file是目录,先把它的下一级干掉,然后删除自己
if (file.isDirectory()) {
File[] all = file.listFiles();
// 循环删除的是file的下一级
for (File f : all) {// f代表file的每一个下级
deleteDirectory(f);
}
}
// 删除自己
file.delete();
}
}

IO流的使用

前言

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

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

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

IO流的分类及体系

流的分类:

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

输入流和输出流:

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

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

节点流和处理流:

  • 直接从数据源或目的地读写数据。
  • 不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。
抽象基类 字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

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

IO流的体系:

节点流的操作步骤

输入操作步骤:

  • 创建File类的对象,指明读取的数据的来源。
    • 要求此文件一定要存在,否则在作为参数传递给输入流的构造器中,在实例化时会抛出FileNotFoundExeception异常。
  • 创建相应的输入流,将File类的对象作为参数,传入流的构造器中。
  • 具体的读入过程:调用read()方法。
    • 创建相应的byte[] 或 char[]。
    • read(byte[] / char[] cbuf)
  • 关闭流资源。

输出操作步骤:

  • 创建File类的对象,指明读取的数据的来源。
    • 如果文件不存在,在调用write()方法时会创建该文件。
  • 创建相应的输出流,将File类的对象作为参数,传入流的构造器中。
    • 第二个参数为boolean类型,可以指明写出到文件是否为追加模式,默认为覆盖模式。
  • 具体的写出过程:调用write方法。
    • write(char[] / byte[] buffer, 0, len)
  • 关闭流资源。

说明:

  • 程序中打开的文件 IO 资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件 IO 资源。

  • 程序中出现的异常需要使用try-catch-finally处理,并且在finally中关闭流资源时需要判断输入流对象是否不为空。

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
@Test
public void test(){
FileReader fr = null;
try {
// 1、File类的实例化
File file = new File("hello.txt");
// 2、FileReader流的实例化
fr = new FileReader(file);
// 3、读入操作
// 每次读取文件中的一个字符,如果达到文件末尾,返回-1
// int data = fr.read();
// while (data != -1){
// System.out.print((char) data);
// data = fr.read();
// }
int data;
while ((data = fr.read()) != -1){
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4、关闭流资源
try {
// 判断流对象是否不为空
if(fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

字节流

InputStream 和 OutputStream 是所有字节流的基类。

FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream 用于读取非文本数据之类的原始字节流。

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:关闭此输入流并释放与该流关联的所有系统资源。

FileOutputStream 从文件系统中的某个文件中获得输出字节。FileOutputStream 用于写出非文本数据之类的原始字节流。

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:关闭此输出流并释放与该流关联的所有系统资源。

非文本文件的复制拷贝:

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 test(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 1、创建File对象,指明读入和读出的文件
File srcFile = new File("hello.webp");
File destFile = new File("hello1.webp");
// 2、创建输入和输出流对象
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] b = new byte[1024];
int len; // 记录每次读入到byte数组中的字符个数
// 3、数据的读入和写出操作
while((len = fis.read(b)) != -1){
fos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 4、关闭流资源
try {
if(fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

字符流

Reader 和 Writer 是所有字符流的基类。

要读取字符流,需要使用 FileReader。

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:关闭此输入流并释放与该流关联的所有系统资源。

要写出字符流,需要使用 FileWriter。

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:关闭此输出流并释放与该流关联的所有系统资源。

文本文件的复制拷贝:

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
37
@Test
public void test(){
FileReader fr = null;
FileWriter fw = null;
try {
// 1、创建File对象,指明读入和读出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello1.txt");
// 2、创建输入和输出流对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
char[] c = new char[5];
int len; // 记录每次读入到char数组中的字符个数
// 3、数据的读入和写出操作
while((len = fr.read(c)) != -1){
fw.write(c, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 4、关闭流资源
if(fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

节点流(或文件流):注意点

  • 在写入一个文件时,如果使用构造器FileOutputStream(file),则目录下有同名文件将被覆盖。
  • 如果使用构造器FileOutputStream(file,true),则目录下的同名文件不会被覆盖, 在文件内容末尾追加内容。
  • 在读取文件时,必须保证该文件已存在,否则报异常。
  • 字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt
  • 字符流操作字符,只能操作普通文本文件。最常见的文本文 件:.txt,.java,.c,.cpp 等语言的源代码。

缓冲流

为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:

  • BufferedInputStream 和 BufferedOutputStream
  • BufferedReader 和 BufferedWriter

缓冲流的理解使用:

  • 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。
  • 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。
  • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满, BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流。
  • 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流。
  • 调用flush()方法手动将buffer中内容写入文件。
  • 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。
  • 在BufferedReader类新增了readLine()方法,直接读取文件的一行内容,不保留原文件换行。在BufferedWriter类新增了newLine()方法,用于写出到文件换行。
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
37
38
39
40
@Test
public void test(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// 1、创建文件对象
File srcFile = new File("hello.webp");
File destFile = new File("hello1.webp");
// 2、创建流对象
// 2.1、创建输入输出流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
// 2.2、创建缓冲流对象
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
// 3、文件的读写操作
byte[] b = new byte[1024];
int len;
while ((len = bis.read(b)) != -1){
bos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4、关闭流资源
// 说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略
try {
if(bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

转换流

转换流提供了在字节流和字符流之间的转换,属于字符流。在创建转换流对象时,第二个参数可以指明编码或解码的字符集,很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

Java API提供了两个转换流:

  • InputStreamReader:将InputStream转换为Reader
  • OutputStreamWriter:将Writer转换为OutputStream
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 test(){
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
// 1、创建输入输出流
FileInputStream fis = new FileInputStream("dbcp.txt");
FileOutputStream fos = new FileOutputStream("dbcp_gbk.txt");
// 2、创建转换流,指定编码和解码方式
isr = new InputStreamReader(fis, "utf-8");
osw = new OutputStreamWriter(fos, "gbk");

// 3、转换:提供字节流与字符流之间的转换
char[] c = new char[10];
int len;
while ((len = isr.read(c)) != -1){
osw.write(c, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4、关闭资源
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

编码集的补充:

  • ASCII:美国标准信息交换码,用一个字节的7位可以表示。
  • ISO8859-1:拉丁码表或欧洲码表,用一个字节的8位表示。
  • GB2312:中国的中文编码表。最多两个字节编码所有字符。
  • GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码。
  • Unicode:国际标准码,融合了目前人类使用的所字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
  • UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。

标准输入输出流

System.inSystem.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
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 OtherStreamTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
// 标准输入流:System.in
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true){
System.out.println("请输入...");
String data = br.readLine();
if("exit".equalsIgnoreCase(data)){
System.out.println("程序结束");
break;
}
System.out.println(data.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

打印流

实现将基本数据类型的数据格式转化为字符串输出。打印流: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
13
14
15
16
17
18
19
20
21
22
23
24
25
@Test
public void test01(){
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps != null) {
// 把标准输出流(控制台输出)改成输出到文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) { // 输出ASCII字符
System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}

数据流

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

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

  • DataInputStream 和 DataOutputStream
  • 分别“套接”在 InputStream 和 OutputStream 子类的流上
  • 其中对于不同的基本数据类型和字符串都定义了不同的方法。
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
@Test
public void test(){
DataOutputStream dos = null;
try {
// 创建数据输出流对象
dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("中国"); // 将字符串或基本数据类型输出到文件
dos.flush();
dos.writeInt(2022);
dos.flush();
dos.writeBoolean(true);
dos.flush();

// 创建数据输入流对象
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
// 读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
String city = dis.readUTF(); // 读取文件中的数据
int year = dis.readInt();
boolean isStudy = dis.readBoolean();
System.out.println("city=" + city + "\n" + "year=" + year + "\n"+"isStudy=" + isStudy);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

对象流

ObjectInputStream 和 OjbectOutputSteam 用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

序列化:用ObjectOutputStream类保存基本类型数据或对象的机制。

反序列化:用ObjectInputStream类读取基本类型数据或对象的机制。

对象序列化机制:允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。

如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,必须实现SerializableExternalizable 接口之一。 否则,会抛出NotSerializableException异常。

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

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

serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@Test
public void test01(){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
// 序列化对象
oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Date());
oos.flush();
oos.writeObject("中国");
oos.flush();
oos.writeObject(new Person(1, "张三"));
oos.flush();

// 反序列化对象
ois = new ObjectInputStream(new FileInputStream("obj.txt"));
Date date = (Date)ois.readObject();
System.out.println(date);
System.out.println((String) ois.readObject());
System.out.println((Person) ois.readObject());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


// 序列化对象需要实现Serializable接口
class Person implements Serializable {
private Integer id;
private String name;

public Person(Integer id, String name) {
this.id = id;
this.name = name;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

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

@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

RandomAccessFile

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

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

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

RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。

RandomAccessFile 类对象可以自由移动记录指针:

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

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

  • r: 以只读方式打开。
  • rw:打开以便读取和写入

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Test
public void test01(){
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("hello.txt", "r");
byte[] b = new byte[10];
int len;
// 游标效果
raf.seek(3);
while ((len = raf.read(b)) != -1){
System.out.println(new String(b,0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

NIO的使用

Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java IO AP。

NIO与原来的IO同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于通道的IO操作。

NIO将以更加高效的方式进行文件的读写操作。

随着 JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。

jdk7提供了Paths类,用来替换原有的File类。

Path类常用方法:

Files类常用方法:

Files类中常用判断的方法:

Files类中常用操作内容的方法: