Java高级应用之---IO流中字节流的输入输出

algorain

流的分类:

按照流的流向来分,可以将流分为输入流和输出流。

  • 输入流:只能从输入流中读取数据,例如scanner
  • 输出流:只能向输出流中写入数据,例如System.out.println

按照流所操作的基本数据单元来分,可以分为字节流和字符流

  • 字节流:所操作的基本数据单元是8位的字节(byte),输入和输出都是对字节进行操作
    • 输入流:InputStream
    • 输出流:OutputStream
  • 字符流:所操作的基本数据单元是16位的字符(Unicode),输入输出都是对字符进行操作
    • 输入流:Reader
    • 输出流:Writer

按照流的角色来分,可以将流分为节点流和处理流

  • 节点流:用于从/向特定的IO设备中读写数据的流,这种流被称为节点流,节点流也称为低级流,节点通常是指文件,内存等其他管道
  • 处理流:对一个已经存在的流进行连接或封装,通过封装后的流来实现数据的读写功能,这种流被称为处理流,处理流也被称为高级流,包装流

注意:

  • 如果进行输入输出的内容是文本内容,则使用字符流

  • 如果进行输入输出的内容是二进制内容,则使用字节流

使用FileInputStream读文件内容

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
package com.qst.chapter01;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
public static void main(String[] args) {
// 声明文件字节输入流
FileInputStream fis = null;
try {
// 实例化文件字节输入流
fis = new FileInputStream(
"src\\com\\rain\\chapter01\\FileInputStreamDemo.java");
// 创建一个长度为1024的字节数组作为缓冲区
byte[] bbuf = new byte[1024];
// 用于保存实际读取的字节数
int hasRead = 0;
// 使用循环重复读文件中的数据
while ((hasRead = fis.read(bbuf)) > 0) {
// 将缓冲区中的数据转换成字符串输出
System.out.print(new String(bbuf, 0, hasRead));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭文件输入流
fis.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}
}

使用FileOutputStream将用户输入的数据写到指定文件中,此方法会新建一个mytest.txt的文件,如果存在mytest.txt就清空里面的内容在输入,如果想要将新的内容追加到文件的末尾,需要使用FileOutputStream(String name, boolean append)构造方法创建一个文件输出流,其中设置append参数的值为true。

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
package com.qst.chapter01;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class FileOutputStreamDemo {
public static void main(String[] args) {
// 建立一个从键盘接收数据的扫描器
Scanner scanner = new Scanner(System.in);
// 声明文件字节输出流
FileOutputStream fos = null;
try {
// 实例化文件字节输出流
fos = new FileOutputStream("D:\\mytest.txt");
System.out.println("请输入内容:");
String str = scanner.nextLine();
// 将数据写入文件中
fos.write(str.getBytes());
System.out.println("已保存!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭文件输出流
fos.close();
scanner.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}
}

  • Title: Java高级应用之---IO流中字节流的输入输出
  • Author: algorain
  • Created at: 2017-02-12 11:50:35
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/02/12/java-article52/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments