假如需要复制一张图片,一份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为转换流,前者将字节流转化为字符流,后者将字符流转化为字节流
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。