java缓冲区输入输出流,提高执行效率,拷贝文件
Posted weixin_ancenhw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java缓冲区输入输出流,提高执行效率,拷贝文件相关的知识,希望对你有一定的参考价值。
//缓冲区输出流
public class FileStream
public static void main(String[] args) throws IOException
// 定义要输出的文本路径
FileOutputStream os = new FileOutputStream("03.txt");
// 定义缓冲区
BufferedOutputStream outputStream = new BufferedOutputStream(os);
outputStream.write("跟你一起去看".getBytes());
outputStream.close();
os.close();
//读取缓冲区输入流
//读取缓冲区输入流
public class FileStream
public static void main(String[] args) throws IOException
FileInputStream inputStream = new FileInputStream("03.txt");
BufferedInputStream is = new BufferedInputStream(inputStream);
int len=0;
byte[] arrChar=new byte[1024];
while ((len=is.read(arrChar))!=-1)
//从0开始转换len定义个数
System.out.print(new String(arrChar,0,len));
//不需要关闭inputStream,is关闭后,会自带关闭不需要关闭inputStream
is.close();
缓冲区拷贝文件执行效率的对比
public class CopyFile
//利用缓冲区实现文件的快速拷贝
public static void main(String[] args) throws IOException
//method01();
method02();
private static void method02() throws IOException
FileInputStream inputStream = new FileInputStream("C:\\\\Users\\\\Administrator\\\\Downloads\\\\本本之家二手交易平台设计与实现.rar");
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream outputStream = new FileOutputStream("bb.rar");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[1024];
int len=0;
long startTime = System.currentTimeMillis();
while ((len=bufferedInputStream.read(bytes))!=-1)
bufferedOutputStream.write(bytes);
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
bufferedInputStream.close();
bufferedOutputStream.close();
public static void method01() throws IOException
FileInputStream inputStream = new FileInputStream("C:\\\\Users\\\\Administrator\\\\Downloads\\\\本本之家二手交易平台设计与实现.rar");
FileOutputStream outputStream = new FileOutputStream("aa.rar");
byte[] arr=new byte[1024];
int len=0;
long startTime = System.currentTimeMillis();
while ((len=inputStream.read(arr))!=-1)
outputStream.write(arr);
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
inputStream.close();
outputStream.close();
缓冲区写入字符
public static void main(String[] args) throws IOException
//字符缓冲写入
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("03.txt"));
for (int i = 0; i < 10; i++)
bufferedWriter.write("hello word "+i);
//换行
bufferedWriter.newLine();
bufferedWriter.close();
读取字符
//读取字符
public static void main(String[] args) throws IOException
//字符缓冲区读出数据
BufferedReader rd = new BufferedReader(new FileReader("03.txt"));
String line;
while ((line=rd.readLine())!=null)
System.out.println(line);
rd.close();
以上是关于java缓冲区输入输出流,提高执行效率,拷贝文件的主要内容,如果未能解决你的问题,请参考以下文章