IO流:读取一个文件
文章目录
1. IO流中的四基类
/ | 字节 | 文本 |
---|---|---|
输入 | InputStream | Reader |
输出 | OutputStream | Writer |
从磁盘读进内存是输入流,从内存写入磁盘是输出流
- 字节流:以字节为单位,可操作任意数据
- 字符流:以字符为单位,只能操作字符数据(取决于当前的字符集)
2. 常见IO流操作
2.1 FileInputStream
打开一个文件流用于读取文件
常用构造方法 | 说明 |
---|---|
FileInputStream(File file) | 通过文件所在路径读取文件 |
【例】读取D盘下的ducument文件夹下的hello.txt
@Test
public void test() throws IOException {
// 通过 File() 读入内存,通过 FileInputStream() 将文件通过流进行操作
FileInputStream fis = new FileInputStream(new File("D:" + File.separator + "document" + File.separator + "hello.txt"));
int data;
// 将hello.txt中的每个字节按ASCII码读取进来,每一个data都是字节对应的ASCII码,当read()方法返回值为-1时,说明已经读到了文件结尾
while ((data = fis.read()) != -1) {
// 将ASCII码转为对应的字符
System.out.print((char) data);
}
}
将hello.txt中的内容输出到控制台
【例】读取resources下的document下的hello.txt
@Test
public void test() throws IOException {
// getResourceAsStream() 用于读取 resources 下的资源,/ 表示 resources 根路径
InputStream is = getClass().getResourceAsStream("/document/hello.txt");
int data;
// 将hello.txt中的每个字节按ASCII码读取进来,每一个data都是字节对应的ASCII码,当read()方法返回值为-1时,说明已经读到了文件结尾
while ((data = is.read()) != -1) {
System.out.print((char) data);
}
}
将hello.txt中的内容输出到控制台
read()
方法为逐一读取数据,效率较低,可以通过byte[]数组的方式从数组中读取数据,改进如下
@Test
public void test() throws IOException {
InputStream is = getClass().getResourceAsStream("/document/hello.txt");
byte[] buffer = new byte[1024];
int length;
// 这里的length,不是返回字节的ASCII码,而是返回buffer中存储的读进来的字节个数
while ((length = is.read(buffer)) != -1) {
for (int i = 0; i < length; i++) {
System.out.print((char) buffer[i]);
}
}
}
将hello.txt中的内容输出到控制台
2.2 ByteArrayOutputStream
用于将字节复制到输出流,通过
toByteArray()
方法将内容存入一个byte[]数组中
@Test
public void test() throws IOException {
InputStream is = getClass().getResourceAsStream("/document/hello.txt");
// 创建字节数组流,可调用 toByteAarray() 将流中内容转为字节数组显示
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
// write() 方法,从 buffer 数组中的第 0 个位置起取 length 个元素
baos.write(buffer, 0, length);
}
System.out.println(new String(baos.toByteArray()));
}
将hello.txt中的内容输出到控制台
2.3 FileOutputStream
打开一个文件流用于输出文件
【例】将字符串输出到D盘下的ducument文件夹下的new.txt
@Test
public void test() throws IOException {
FileOutputStream fos = new FileOutputStream(new File("D:" + File.separator + "document" + File.separator + "new.txt"));
String str = "This is a new file";
fos.write(str.getBytes());
fos.close();
}
2.4 BufferInputStream/BufferOutputStream
缓冲流,套用在文件流上加快传输速率
【例】将D盘下的ducument文件夹下的hello.txt移动到E盘下
@Test
public void test19() throws IOException {
String readPath = "D:" + File.separator + "document" + File.separator + "hello.txt";
String writePath = "D:" + File.separator + "hello.txt";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(readPath)));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(writePath)));
byte[] buffer = new byte[1024];
int length;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
}