您的位置:首页 > 编程语言 > Java开发

Java字节流 从文件输入输出到文件过程解析

2019-10-16 18:07 1681 查看

假如需要复制一张图片,一份word,一个rar包。可以以字节流的方式,读取文件,然后输出到目标文件夹。

以复制一张4M的图片举例。

每次读一个字节:

ch = (char)System.in.read(); //读入一个字符,返回读到的字节的int表示方式,读到末尾返回-1

复制时候一个字节一个字节的读取、写入,这样是很慢的。设置一个用来缓冲的字符数组,会让复制的过程快很多(每次读入的字节变多)。

方便阅读,类的名称用中文描述

import java.io.*;
public class 字节流的缓冲区 {
public static void main(String[] args) throws Exception {
FileInputStream in=new FileInputStream("E:\\photo\\IMG.jpg");
//FileOutputStream中的文件不存在,将自动新建文件
OutputStream out=new FileOutputStream("E:\\test.jpg");
byte[] buff=new byte[1024];
int b;
long beginTime=System.currentTimeMillis();
while ((b=in.read(buff))!=-1) {
out.write(buff,0,b);
}
long endTime=System.currentTimeMillis();
System.out.println("运行时长为: "+(endTime-beginTime)+"毫秒");
in.close();
out.close();
System.out.println("正常运行!");
}
}

这里设置的字节数组是1024个字节。复制的时间比一个字节一个字节的复制快很多。

//封装了FileOutputStream管道之后,三种函数参数
//write(b) 写入一个b
//write(byte[] b) 将字节数组全部写入
//write(byte[] b,int off,int len) 例如write(byteTest,0,len)表示数组byteTest中从0开始长度为len的字节
//一般都用第3个

字节缓冲流

用BufferedInputStream和BufferedOutputStream来封装FileInputStream和FileOutputStream

方便阅读,类的名称用中文描述

import java.io.*;
public class 字节缓冲流 {
public static void main(String[] args) throws Exception {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("E:\\photo\\IMG.jpg"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("E:\\test.jpg"));
int len;
long begintime=System.currentTimeMillis();
while((len=bis.read())!=-1) {
bos.write(len);
}
long endtime=System.currentTimeMillis();
System.out.println("运行时间为:"+(endtime-begintime)+"毫秒");
bis.close();
bos.close();
System.out.println("正常运行");
}
}

将String类的对象用字节流写入文件时

import java.io.*;
public class outFile {
public static void main(String[] args) throws Exception {
FileOutputStream out=new FileOutputStream("example.txt");
String str="测试";
byte[] b=str.getBytes();
for(int i=0;i<b.length;i++) {
out.write(b[i]);
}
out.close();
System.out.println("输出成功");
}
}

当需要以附加的形式写入文件时

FileOutputStream out=new FileOutputStream("example.txt",true);

转换流

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String x = in.read();

InputSteamReader和OutputStreamReader为转换流,前者将字节流转化为字符流,后者将字符流转化为字节流

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息