上文中我们讲了Reader,Writer,InputStream,OutputStream这四种流的基本用法🔢
【Java】文件I/O-文件内容操作-输入输出流-Reader/Writer/InputStream/OutputStream四种流
其中InputStream和OutputStream两个类涉及到的都是byte(字节),操作并不方便,下面我们就讲一下怎样把字节流转换成字符流📑
1、输入
InputStream输入读取文本数据时,读取的是二进制字节数据,为了转化成文字,我们利用Scanner类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class demo7 {
public static void main(String[] args) {
try(InputStream inputStream = new FileInputStream("/Users/liuwenwen/Desktop/test.txt")) {
Scanner scanner = new Scanner(inputStream);
String s = scanner.next();
System.out.println(s);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Scanner类中我们常填的System.in参数本身也是一个InputStream,因此我们在这里只需要直接把inputStream当做参数传入。这样操作后,我们就从文本而不是键盘读取数据了。
读取到的数据直接转换成字符流
2、输出
OutputStream则是采用PrintWriter类来进行转换的
import java.io.*;
public class demo9 {
public static void main(String[] args) {
try (OutputStream outputStream = new FileOutputStream("/Users/liuwenwen/Desktop/test.txt",true)){
PrintWriter writer = new PrintWriter(outputStream);
writer.println("借问桃将李,相乱欲何如。");
writer.flush();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
写入结果