java基础-IO流

file类

文件需要用一个对象表示,那这就需要file类来创建对象了。

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

file类的理解

1.File类的一个对象,代表一个文件或一个文件目录

2.File类声明在java.io下

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

4.后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的“终点”。

file类的实例化

1.常用构造器

File(String filepath)

File(String parentPath,String childPath)

File(File parentFile,String childPath)

2.路径:

相对路径,绝对路径

注意

IDEA下:

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

如果使用main方法测试,相对路径即为当前的Project下。

eclipse下:

相对路径都是Project下

3.路径分隔符

windows和DOS系统默认使用“\”来表示

UNIX和URL使用“/”来表示

Java程序支持跨平台运行,因此路径分隔符要慎用。

4.常用方法

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数组

File类的重命名功能

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

File类的判断功能

public boolean isDirectory():判断是否是文件目录

public boolean isFile() :判断是否是文件

public boolean exists() :判断是否存在

public boolean canRead() :判断是否可读

public boolean canWrite() :判断是否可写

public boolean isHidden() :判断是否隐藏

File类的创建功能

public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false

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

public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目 路径下。

File类的删除功能

public boolean delete():删除文件或者文件夹 删除注意事项: Java中的删除不走回收站。 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录

JavaIO流

原理

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

我们应该站在程序(内存)的角度,分清使用输入还是输出。

流的分类

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

字符流适用于文本 (例如 .txt,.cpp),

字节流适用于 图,视频等

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

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

直接作用于文件上的是节点流

包了一层流的,外面的流就是处理流。

1574940557657

其中前面两行(抽象基类,访问文件)是节点流

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

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

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

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

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.建立一个流对象,将已存在的一个文件加载进流。

FileReader fr = new FileReader(new File(“Test.txt”));
2.创建一个临时存放数据的数组。

char[] ch = new char[1024];
3.调用流对象的读取方法将流中的数据读入到数组中。

fr.read(ch);

4.关闭资源。

fr.close();

注意点

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

写入文件

1.创建流对象,建立数据存放文件

FileWriter fw = new FileWriter(new File(“Test.txt”));
2.调用流对象的写入方法,将数据写入流

fw.write(“atguigu-songhongkang”);
3.关闭流资源,并将流中的数据清空到文件中。

fw.close();

字符流

练习 FileReaderWriter

代码:

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package IO;

import org.junit.Test;
import sun.reflect.generics.tree.VoidDescriptor;

import javax.annotation.processing.Filer;
import java.io.*;

/**
* @author lh
* create 2019-11-28-19:54
*/
public class FileReaderWriterTest {
/*
1.read的理解:返回读入的一个字符,如果达到文件末尾,返回-1; 如:读a 返回97,所以我们可以使用(char)转一下,就是a了
2.异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
3.读入的文件要存在,不然报异常
*/

@Test
public void testFileReader() {
FileReader fileReader = null;
try {
//1.实例对象
File file = new File("hello.txt");
//2.提供具体的流
fileReader = new FileReader(file);

//3.数据读入
int data;
while ((data = fileReader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//对read()操作升级:使用read的重载方法
@Test
public void testFileReadeer1() {
FileReader fileReader = null;
try {
File file = new File("hello.txt");
fileReader = new FileReader(file);

char[] cbuf = new char[5];
int len;
while ((len = fileReader.read(cbuf)) != -1) {
//方式一:
//错误的写法,因为数组是覆盖的写入,空的没进行覆盖,就会输出之前的字符
// for (int i = 0; i < cbuf.length; i++) {
// System.out.print(cbuf[i]);
// }
//输出:
/*
hello word

hello123lo1
*/
// for (int i = 0; i < len; i++) { //正确写法
// System.out.print(cbuf[i]);
// }
//方式二:
//错误的,和上面错误一样
// String str = new String(cbuf);
// System.out.print(str);
//正确写法:
String str = new String(cbuf, 0, len);
System.out.print(str);

}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null) {

try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}


}

/*
输出操作对应的file可以不存在,在输出的过程中自动创建。
如果存在,
1.如果构造器是:FileWriter(file,false)或者FileWriter(file) :
覆盖。(文件覆盖,就算覆盖前文件比较长,也全覆盖。)
2.如果构造器是:FileWriter(file,true),原有的基础上追加输出

*/
@Test
public void testFileWrite() {
FileWriter fw = null;
try {
File file = new File("hello1.txt");
fw = new FileWriter(file, false);
fw.write("have gg");
// fw.write("good" );
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close(); //不关闭的话,会发现文件创建了但是空的。
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

@Test
public void testFileReaderWriter() throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
File src = new File("hello.txt");
File des = new File("hello2.txt");

fr = new FileReader(src);
fw = new FileWriter(des);

//数据的读入和写出操作
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf))!= -1 ){
//每次写出len个字符
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
//1.
/*
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/

//2
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

字节流

FileIOstream

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package IO;

import org.junit.Test;

import java.io.*;

/**
* @author lh
* create 2019-11-26-20:16
*/
public class FileIOstream {
@Test
//使用字节流 FileInput处理字节文件可能出现乱码
public void testFileInputOutputStreamTest() {
FileInputStream fileInputStream = null;
FileInputStream fis = null;

try {
//1.造文件
File file = new File("hello.txt");

//2.造流
fis = new FileInputStream(file);

//3.读数据
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
String str = new String(buffer, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
/*
实现对图的复制操作
*/
public void testFileInputOutputStream(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File src = new File("1.jpg");
File des = new File("2.jpg");

fis = new FileInputStream(src);
fos = new FileOutputStream(des);

//复制
int len;
byte[] buffer =new byte[5];
while ((len = fis.read(buffer)) != -1) {

fos.write(buffer,0,len);
//因为不能字节输出数组到屏幕,所以创建一个str字符串来获取数据用以输出或者for来完成,但是write有处理数组的能力所以不用。
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//指定路径改下文件的复制
public void copeFile(String srcpath,String despath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File src = new File(srcpath);
File des = new File(despath);

fis = new FileInputStream(src);
fos = new FileOutputStream(des);

//复制
int len;
byte[] buffer =new byte[1024];
while ((len = fis.read(buffer)) != -1) {

fos.write(buffer,0,len);
//因为不能字节输出数组到屏幕,所以创建一个str字符串来获取数据用以输出或者for来完成,但是write有处理数组的能力所以不用。
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
@Test
public void testCopefile(){
long start = System.currentTimeMillis();
String srcpath = "C:\\Users\\华\\Desktop\\1.avi";
String descpath = "C:\\Users\\华\\Desktop\\2.avi";
copeFile(srcpath,descpath);

long end =System.currentTimeMillis();

System.out.println("复制操作花费的时间为" +(end - start));
}
}

1.read的理解:

2

最简单的read():

返回读入的一个字符,如果达到文件末尾,返回-1; 如:读a 返回97,所以我们可以使用(char)转一下,就是a了

read(char[] buf):返回每次读入数值的字符个数,如果到末尾,返回-1,每次将读到的赋给buf数组

1574944758898

2.异常的处理:

为了保证流资源一定可以执行关闭操作。需要使用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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//指定路径改下文件的复制
public void copeFile(String srcpath,String despath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File src = new File(srcpath);
File des = new File(despath);

fis = new FileInputStream(src);
fos = new FileOutputStream(des);

//复制
int len;
byte[] buffer =new byte[1024];
while ((len = fis.read(buffer)) != -1) {

fos.write(buffer,0,len);
//因为不能字节输出数组到屏幕,所以创建一个str字符串来获取数据用以输出或者for来完成,但是write有处理数组的能力所以不用。
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
@Test
public void testCopefile(){
long start = System.currentTimeMillis();
String srcpath = "C:\\Users\\华\\Desktop\\1.avi";
String descpath = "C:\\Users\\华\\Desktop\\2.avi";
copeFile(srcpath,descpath);

long end =System.currentTimeMillis();

System.out.println("复制操作花费的时间为" +(end - start));
}

字符流与字节流的使用:

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

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

处理流

缓冲流buffer

1.

BufferedInputStream
BufferedOutputStream
BufferedReader
BufeeredWriter

2.作用:
提供流的读取,写入的速度

3.处理流,就是“套接”在已有的流的基础上

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package IO;

import org.junit.Test;

import java.io.*;

/**
* 1.
* BufferedInputStream
* BufferedOutputStream
* BufferedReader
* BufeeredWriter
* <p>
* 2.作用:
* 提供流的读取,写入的速度
* <p>
* 3.处理流,就是“套接”在已有的流的基础上
*
* @author lh
* create 2019-11-29-19:03
*/
public class BufferedTest {
/*
实现非文件的复制
*/
@Test
public void testcopy() {
long start = System.currentTimeMillis();
String srcpath = "C:\\Users\\华\\Desktop\\1.avi";
String descpath = "C:\\Users\\华\\Desktop\\3.avi";
copyBufferedStreamTest(srcpath, descpath);
long end = System.currentTimeMillis();

System.out.println("复制操作花费的时间为" + (end - start));
}

public void copyBufferedStreamTest(String srcpath, String despath) {
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;


try {
//1.造文件
File srcf = new File(srcpath);
File descf = new File(despath);

//2.造流
//2.1 造节点流
FileInputStream fileInputStream = new FileInputStream(srcf);
FileOutputStream fileOutputStream = new FileOutputStream(descf);

//2.2造缓冲流
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);


//3.复制的细节:读取,写入
byte[] buffer = new byte[1024];
int len;
while ((len = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, len);

}
} catch (IOException e) {
e.printStackTrace();
} finally {
//资源的关闭
//要求:先关闭外层的流,再关闭,内层的流
if (bufferedInputStream != null) {

try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

}
//说明:在关闭外层的流的同时,内层流也会自动的进行关闭。关于内层流的关闭,可以省略
// fileInputStream.close();
// fileOutputStream.close();
}

}

@Test
public void testBufferedRW() {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;

try {
/*
使用BufferedReader和BufferedWriter
*/
bufferedReader = new BufferedReader(new FileReader(new File("hello.txt")));
bufferedWriter = new BufferedWriter(new FileWriter(new File("hello3.txt")));

//读写
// //方式一:使用char[]数组
// char[] cbuf = new char[1024];
//
// int len;
// while ((len = bufferedReader.read(cbuf)) != -1) {
// bufferedWriter.write(cbuf, 0, len);
// // bufferedWriter.flush();
// }

//方式二
String data;
while ((data = bufferedReader.readLine()) != null) {
// //方法一
// bufferedWriter.write(data +"\n"); //data中不包含换行符

//方法二
bufferedWriter.write(data);
bufferedWriter.newLine();

}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedWriter != null) {
try {
bufferedWriter.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
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
76
77
78
package IO;
import org.junit.Test;

import java.io.*;

/**
* 处理流之二:转换流的使用
* 1.转换流 :属于字符流
* InputStreamReader:将一个字节的输入流转换为字符的输入流
* OutputSreamWriter:将一个字符的输出流转换为字节的输出流
* <p>
* 2.作用:提供字节流与字符流之间的转换
* <p>
* 3.解码:字节、字节数组 -->字符数组、字符串
* 编码:字符数组、字符串 -->字节、字节数组
*
* 4.字符集
* ASCII美国信息交换标准代码。
* 用1个字节的7可以表示。
* ISO8859-1:拉丁码表。欧洲码表
* 用一个字节的8位表示。
* GB2312:中国中文编码表。最多两个字节编码所有字符。
* GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码。
* Unicode:国际标准编码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。2 16
* UTF-8:变长的编码方式,可以用1-4个字节来表示一个字符。(中文3个字节)
*
*
* @author lh
* create 2019-11-30-12:42
*/
public class InputsreamReaderTest {
@Test
//实现字节输入流到字符输出流的转换
//处理异常应该使用try-chatch-finnally,这里就不改了
public void test1() throws IOException {
FileInputStream fis = new FileInputStream("dbcp.txt");
// InputStreamReader isr =new InputStreamReader(fis);//使用系统默认的字符集
//参数2指明了字符集
InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); //使用哪个字符集取决于文件本身的字符集

char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
String str = new String(cbuf, 0, len);
System.out.print(str);
}
if (isr != null) {
isr.close();
}
}

@Test
//处理异常应该使用try-chatch-finnally,这里就不改了
public void test2() throws IOException {
//1.造文件、造流
File file1 = new File("dbcp.txt");
File file2 = new File("dbcp_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");

//2.读写过程
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
osw.write(cbuf, 0, len);
}

//3.关闭
isr.close();
osw.close();
//关闭操作时要注意关闭的对象,关错了会导致复制的文件为空。

}
}

标准输入输出流

  • 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)

打印流

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

  • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
  • PrintStream和PrintWriter的输出不会抛出IOException异常
  • PrintStream和PrintWriter有自动flush功能
  • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。 在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
  • System.out返回的是PrintStream的实例

数据流

为了方便地操作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
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
package IO;

import org.junit.Test;


import javax.naming.Name;
import javax.swing.*;
import java.io.*;

/**
* 数据流:用于读取或写入基本数据类型的变量或字符串
* @author lh
* create 2019-11-30-17:07
*/
public class DataStream {
@Test
//将内存中的字符串、基本数据类型的变量写出到文件中
public void test1() throws IOException {
//1.
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));

//2.
dos.writeUTF("小王");
dos.flush(); //刷新操作,将内存中的数据写入文件
dos.writeInt(23);
dos.flush();
dos.writeBoolean(true);
dos.flush();

//3.
dos.close();
}
/*
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致。
*/
@Test
public void test2() throws IOException {
//1.
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));

//2.
String str = dis.readUTF();
int age = dis.readInt();
boolean ismale = dis.readBoolean();

System.out.println("name = " + str);
System.out.println("age = " + age);
System.out.println("is male ="+ ismale);
}
}

对象流

ObjectInputStream和OjbectOutputSteam

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

  • 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
  • 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
  • ObjectOutputStream和ObjectInputStream不能序列化static和transient修 饰的成员变量

小结

  • 一、流的分类:

  • 1.操作数据单位:字节流、字符流

  • 2.数据的流向:输入流、输出流

  • 3.流的角色:节点流、处理流

  • 二、流的体系结构

抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer))
OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush()
Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush()

处理流的输出有一个刷新功能,如:

在BufferedOutputStream中有一个flush()方法:刷新缓冲区

补充:字符集

1575100285486

1575100352643