取出:
其实就是给了一个数组,每次读取、写入的时候不再是一次取一个字节,而是取指定大小数组的字节。
package io;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @ClassName BufferedInputStreamA
* @Author 瞿肖
* @Date 2022/7/8 9:48
*/
public class BufferedInputStreamA {
public static void main(String[] args) {
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\我的电脑\\asd\\a.txt"));
byte[] arr = new byte[1024];
int len = 0;
while ((len = bis.read(arr)) != -1) {
System.out.println(new String(arr, 0, len));
}
System.out.println("***********");
bis = new BufferedInputStream(new FileInputStream("D:\\我的电脑\\asd\\a.txt"));
while ((len = bis.read()) != -1) {
System.out.print((char) (len));
}
bis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
本类就是FileInputStream的加强版,细节和它一样,也是取出的时候可以传入一个数组,这样比FileInputStream更快,使用单个字节取出时,也不能取出汉字,会乱码
写入:
package io;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @ClassName BufferedOutputStreamA
* @Author 瞿肖
* @Date 2022/7/8 10:10
*/
public class BufferedOutputStreamA {
public static void main(String[] args) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\我的电脑\\asd\\a.txt"));
byte[] arr = "村上春树".getBytes(StandardCharsets.UTF_8);
bos.write(arr, 0, arr.length);
bos.flush();
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
这里也不多说,和前面的FileOutputStream也是一样,就是提高了写入的速度。
注意close()自带一次刷新功能
文件处理:
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class test1 {
@Test
public void t1() throws Exception {
//便利指定文件夹,检测文件里包含‘张三’关键字的文件,放在:D:\桌面\iotest\t1.txt
File f = new File("D:\\桌面\\sj");
dfs(f);
out.flush();
out.close();
}
BufferedInputStream in = null;
static BufferedOutputStream out = null;
static {
try {
out = new BufferedOutputStream(new FileOutputStream(new File("D:\\桌面\\iotest\\t1.txt"), true));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
byte[] arr = new byte[10240];
private void dfs(File f) throws Exception {
int leng = 0;
if (!f.isDirectory()) {
return;
}
File[] files = f.listFiles();
for (File p : files) {
if (p.isDirectory()) {
dfs(p);
} else {
//发现文件,取出文件,读取数据。
in = new BufferedInputStream(new FileInputStream(p));
StringBuilder str = new StringBuilder();
while ((leng = in.read(arr)) != -1) {
str.append(new String(arr, 0, leng));
}
String s = str.toString();
if (s.contains("张三")) {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write("\r\n".getBytes());
// FileWriter fw = new FileWriter("D:\\桌面\\iotest\\t1.txt", true);
// fw.write(s + "\r\n");
// fw.flush();
// fw.close();
}
}
}
}
}