字符流与字节流

字节流和字符流的概念

Java对于文件处理是按照流的方式进行操作的(和C++ 类似 都会用到一个缓冲区),按照处理数据的单位可以分为字节流和字符流。

按照输入输出的方向可以分为输入流和输出流。

字节流:每次读入或输出的是8位二进制。

字符流:每次读入或输出的是16位二进制,即两个字节。

根据Java API规范

FileOutputStream用于写入原始字节流,例如图像数据。

FileWriter,用于编写字符流,例如写文本。

节点流与处理流

File对象

创建文件对象相关构造器和方法

1
2
3
new File(String pathname)                    //根据路径构建一个File对象
new File(File paraent, String child) //根据父目录文件+子路径构建
new File(String parent, String child) //根据父目录-子路径构建

在E盘下三种创建文件的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
第一种:
String filePath = "e:\\news1.txt";
File file = new File(filePath);
file.createNewFile();

第二种:
File parentFile = new File("e:\\");
String fileName = "news2.txt";
//这里的 file 对象,在 java 程序中,只是一个对象
//只有执行了 createNewFile 方法,才会真正的,在磁盘创建该文件
File file = new File(parentFile, fileNa
file.createNewFile();me);

第三种:
String parentPath = "e:\\";
String fileName = "news4.txt";
File file = new File(parentPath, fileName);
file.createNewFile()

获取文件的相关信息的API

1
2
3
4
5
6
7
8
9
10
11
//先创建文件对象
File file = new File("e:\\news1.txt");
//调用相应的方法,得到对应信息
System.out.println("文件名字=" + file.getName());
//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
System.out.println("文件绝对路径=" + file.getAbsolutePath());
System.out.println("文件父级目录=" + file.getParent());
System.out.println("文件大小(字节)=" + file.length());
System.out.println("文件是否存在=" + file.exists());//T
System.out.println("是不是一个文件=" + file.isFile());//T
System.out.println("是不是一个目录=" + file.isDirectory());//F

FileInputStream(字节流,文件专属)

使用FileInputStream读取hello.text文件

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
第一种:
/**
* 单个字节的读取,效率比较低
*/
String filePath = "e:\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = null;
//创建 FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
//如果返回-1 , 表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char)readData);//转成 char 显示
}
//关闭文件流,释放资源.
fileInputStream.close();


第二种:
/**
* 使用 read(byte[] b) 读取文件,提高效率
*/
String filePath = "e:\\hello.txt";
//字节数组
byte[] buf = new byte[8]; //一次读取 8 个字节. int readLen = 0;
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多 b.length 字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
//如果返回-1 , 表示读取完毕
//如果读取正常, 返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf, 0, readLen));//显示
}
fileInputStream.close();

FileOutputStream(字节流,文件专属)

使用 FileOutputStream 在 a.txt 文件,中写入 “hello,world”.

如果文件不存在,会创建文件(注意:前提是目录已经存在.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//创建 FileOutputStream 对象
String filePath = "e:\\a.txt";
FileOutputStream fileOutputStream = null;
//得到 FileOutputStream 对象 对象
//1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
//2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
fileOutputStream = new FileOutputStream(filePath, true);

//写入一个字节
fileOutputStream.write('H');

//写入字符串
String str = "hsp,world!";
//str.getBytes() 可以把 字符串-> 字节数组
//fileOutputStream.write(str.getBytes());

//write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
fileOutputStream.write(str.getBytes(), 0, 3);
fileOutputStream.close();

完成图片/音乐的拷贝.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//1. 创建文件的输入流 , 将文件读入到程序
//2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件.
String srcFilePath = "e:\\Koala.jpg";
String destFilePath = "e:\\Koala3.jpg";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream = new FileOutputStream(destFilePath);

//定义一个字节数组,提高读取效果
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1) {
//读取到后,就写入到文件 通过 fileOutputStream
//即,是一边读,一边写
fileOutputStream.write(buf, 0, readLen);//一定要使用这个方法
}
fileInputStream.close();
fileOutputStream.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
33
34
35
36
37
38
39
40
41
/**
MultipartFile是SpringMVC提供简化上传操作的工具类
在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据
文件是以二进制流传递到后端的,然后需要我们自己转换为File类。
*/
//将网页的上传的图片保存到服务器
public R<String> upload(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
String filePath = UUID.randomUUID().toString() + substring;
File dir = new File(basePath);
//判断目录是否存在,若不存在则创建
if(!dir.exists()) {
dir.mkdirs();
}
try {
file.transferTo(new File(basePath + filePath));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(filePath);
}

//将从网页保存的图片回显到网页
public void download(String name, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
int len = 0;
byte[] bytes = new byte[1024];
while((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

FileReader(字符流,文件专属)

使用 FileReader 从 story.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
第一种:
/**
单个字符读取文件
*/
String filePath = "e:\\story.txt";
FileReader fileReader = null;
int data = 0;
//1. 创建 FileReader 对象
fileReader = new FileReader(filePath);
//循环读取 使用 read, 单个字符读取
while ((data = fileReader.read()) != -1) {
System.out.print((char) data);
}
fileReader.close();

第二种:
/**
字符数组读取文件
*/
String filePath = "e:\\story.txt";
FileReader fileReader = null;
int readLen = 0;
char[] buf = new char[8];
//1. 创建 FileReader 对象
fileReader = new FileReader(filePath);
//循环读取 使用 read(buf), 返回的是实际读取到的字符数
//如果返回-1, 说明到文件结束
while ((readLen = fileReader.read(buf)) != -1) {
System.out.print(new String(buf, 0, readLen));
}
fileReader.close();

FileWriter(字符流,文件专属)

使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
String filePath = "e:\\note.txt";
//创建 FileWriter 对象
FileWriter fileWriter = null;
char[] chars = {'a', 'b', 'c'};
fileWriter = new FileWriter(filePath);//默认是覆盖写入
// 3) write(int):写入单个字符
fileWriter.write('H');
// 4) write(char[]):写入指定数组
fileWriter.write(chars);
// 5) write(char[],off,len):写入指定数组的指定部分
fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
// 6) write(string):写入整个字符串
fileWriter.write("风雨之后,定见彩虹");
// 7) write(string,off,len):写入字符串的指定部分
fileWriter.write("上海天津", 0, 2);
//fileWriter.flush();
//关闭文件流,等价 flush() + 关闭
fileWriter.close();

BufferedReader和BufferedWriter(字符流)

综合使用BufferedReader和BufferedWriter完成文本文件拷贝,注意文件编码

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
//1. BufferedReader 和 BufferedWriter 是安装字符操作
//2. 不要去操作 二进制文件[声音,视频,doc, pdf ], 可能造成文件损坏
//BufferedInputStream
//BufferedOutputStream
String srcFilePath = "e:\\a.java";
String destFilePath = "e:\\a2.java";

BufferedReader br = null;
BufferedWriter bw = null;
String line;//按行读取, 效率高
//创建 bufferedReader, new BufferedReader(FileReader filerReader)
br = new BufferedReader(new FileReader(srcFilePath));

//创建 BufferedWriter, new BufferedWriter(FileWriter filerWriter)
//1. new FileWriter(filePath, true) 表示以追加的方式写入
//2. new FileWriter(filePath) , 表示以覆盖的方式写入
bw = new BufferedWriter(new FileWriter(destFilePath));

//1. bufferedReader.readLine() 是按行读取文件
//2. 当返回 null 时,表示文件读取完
//3. readLine 读取一行内容,但是没有换行
while ((line = br.readLine()) != null) {
//每读取一行,就写入
bw.write(line);
//插入一个换行
bw.newLine();
}
System.out.println("拷贝完毕...");
//关闭流
br.close();
bw.close();

BufferedOutputStream和BufferedInputStream(字节流)

在创建流对象时会创建一个内部缓冲区数组.

使用BufferedOutputStream和BufferedInputStream,完成二进制文件拷贝.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
String srcFilePath = "e:\\a.jpg";
String destFilePath = "e:\\a3.jpg";
//创建 BufferedOutputStream 对象 BufferedInputStream 对象
BufferedInputStream bis = null;
BufferedOutputStream bos = null;

//因为 FileInputStream 是 InputStream 子类
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
//循环的读取文件,并写入到 destFilePath
byte[] buff = new byte[1024];
int readLen = 0;
//当返回 -1 时,就表示文件读取完毕
while ((readLen = bis.read(buff)) != -1) {
bos.write(buff, 0, readLen);
}
System.out.println("文件拷贝完毕~~~");
//关闭流 , 关闭外层的处理流即可,底层会去关闭节点流
bis.close();
bos.close();

BufferedStream与FileStream

谁快谁慢是根据实际情况来决定的,而不是说带了缓冲区就一定快;

  • 每次写入的数据量小的情况下,带缓冲区的BufferedOutputStream效率更快;
  • 每次写入的数据量比较大时,不带缓冲区的 FileOutputStream 效率更快;

所以,大家在选择的时候就需要根据实际情况来决定使用哪种IO流了,而大部分情况下,FileOutputStream 就已经足够了,只需要将写入的数据量大一点即可;

对象流-ObjectInputStream 和 ObjectOutputStream

功能:提供了对基本类型或对象类型的序列化和反序列化的方法

    ObjectOutputStream 提供 序列化功能

    ObjectInputStream 提供 反序列化功能

演示 ObjectOutputStream 的使用, 完成数据的序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
//序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
String filePath = "e:\\data.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到 e:\data.dat
oos.writeInt(100);// int -> Integer (实现了 Serializable)
oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
oos.writeChar('a');// char -> Character (实现了 Serializable)
oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
oos.writeUTF("韩顺平教育");//String
//保存一个 dog 对象
oos.writeObject(new Dog("旺财", 10, "日本", "白色"));
oos.close();
System.out.println("数据保存完毕(序列化形式)");

使用ObjectInputStream读取data.dat并反序列化恢复数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1.创建流对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\data.dat"));
// 2.读取, 注意顺序
System.out.println(ois.readInt());
System.out.println(ois.readBoolean());
System.out.println(ois.readChar());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
// 3.关闭
ois.close();
System.out.println("以反序列化的方式读取(恢复)ok~");

转换流-InputStreamReader 和 OutputStreamWriter

将字节流FileInputStream包装成(转换成)字符流InputStreamReader,对文件进行读取(按照utf-8/gdk格式),进而再包装成BufferedReader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String filePath = "e:\\a.txt";
//1. 把 FileInputStream 转成 InputStreamReader
//2. 指定编码 gbk
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//3. 把 InputStreamReader 传入 BufferedReader
//BufferedReader br = new BufferedReader(isr);
//将 2 和 3 合在一起
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "gbk"));
//4. 读取
String s = br.readLine();
System.out.println("读取内容=" + s);
//5. 关闭外层流
br.close();

将字节流FileOutputStream包装成(转换成)字符流OutputStreamWriter,对文件进行读取(按照utf-8/gdk格式),进而再包装成BufferedWriter

1
2
3
4
5
6
7
// 1.创建流对象
OutputStreamWriter osw =
new OutputStreamWriter(new FileOutputStream("d:\\a.txt"), "gbk");
// 2.写入
osw.write("hello,world");
// 3.关闭
osw.close();

Properti类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//使用 Properties 类来读取 mysql.properties 文件
//1. 创建 Properties 对象
P//roperties properties = new Properties();
//2. 加载指定配置文件
properties.load(new FileReader("src\\mysql.properties"));
//3. 把 k-v 显示控制台
properties.list(System.out);
//4. 根据 key 获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
//5.使用 Properties 类来创建 配置文件, 修改配置文件内容
properties.setProperty("charset", "utf8");
properties.setProperty("user", "汤姆");//注意保存时,是中文的 unicode 码值
properties.setProperty("pwd", "888888");
//将 k-v 存储文件中即可
properties.store(new FileOutputStream("src\\mysql2.properties"), null);