缓冲流
字节缓冲流: BufferedInputStream, BufferedOutputStream
字符缓冲流: BufferedReader, Bufferedwroter
字节缓冲流
其构造方法
//创建字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream (new FileInputStream("aa.txt"));
//创建字节缓冲输出流
BufferedOutputStream bis = new BufferedOutputStream (new FileOutputStream("aa.txt"))
如使用字节缓冲流拷贝文件(使用数组的方式效率更高)
import java.io.*;
public class CopyDemoOne {
public static void main(String[] args) throws FileNotFoundException {
//记录时间
long start = System.currentTimeMillis();
//创建流对象
try(BufferedInputStream src = new BufferedInputStream(new FileInputStream("C:\\Users\\admin\\Desktop\\132.apk"));
BufferedOutputStream copy = new BufferedOutputStream(new FileOutputStream("G:\\aaa.apk"));) {
//读取数据
int len;
byte[] bytes = new byte[8*1024];
while ((len = src.read(bytes)) != -1){
copy.write(bytes,0,len);
}
}catch (IOException e){
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("runtime: " + (end - start) + "ms");
}
}
使用数组复制时间只用了428ms(274M的文件)
若不使用数组,那么拷贝时间将会增加很多
import java.io.*;
public class FileCopyDemoTwo {
public static void main(String[] args) throws FileNotFoundException {
//记录时间
long start = System.currentTimeMillis();
//创建流对象
try (
BufferedInputStream src = new BufferedInputStream(new FileInputStream("C:\\Users\\admin\\Desktop\\132.apk"));
BufferedOutputStream copy = new BufferedOutputStream(new FileOutputStream("G:\\aaa.apk"));) {
//读取数据
int len;
while ((len = src.read()) != -1) {
copy.write(len);
}
} catch (
IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("runtime: " + (end - start) + "ms");
}
}
若使用FileInputStream / FileOutputStream 来进行操作要更久,效率是极为缓慢
字符缓冲流
构造方法
BufferedReader(Reader in) : 创建一个新的缓冲输入流
BuffereWriter(writer out) : 创建一个新的缓冲输出流
其构造的方式
//创建字符缓冲输入流
BufferedReader ber = new BufferedReader(new FileReader("G:\\aaa.txt"));
//创建字符缓冲输出流
BufferedWriter bwr = new Bufferedwriter(new FileWriter("G:\\aaa.txt"));
方法
BufferedReader : readLine() : 读一行文字
BufferedReader : newLine() : 是换行
readLine(): 读一行
原文件:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadLine {
public static void main(String[] args) throws IOException {
//创建输入流
BufferedReader br = new BufferedReader(new FileReader("G:\\aaa.txt"));
String line = null;
while ((line = br.readLine()) != null){
System.out.println(line);
System.out.println("***********");
}
br.close();
}
}
输出:
newline(): 换行
public class FilenewlLine {
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("G:\\test.txt"));
//写出数据到文件
bufferedWriter.write("我们都是好孩子");
//换行
bufferedWriter.newLine();
bufferedWriter.write("我们都是好孩子");
//换行
bufferedWriter.newLine();
//关闭资源
bufferedWriter.close();
}
}
输出: