1.通过创建一个指定长度的字节数组作为缓冲区(适用于读写较大图片时缓冲区的定义 ,相当于把文件分批次打包带走,相对于普通的效率快)。注意:缓冲区的长度一定是2的整数幂。
public static void main(String[] args) {
FileInputStream fis=null;
int item=0;
FileOutputStream fos=null;
try{
//创建字节输入流对象
fis=new FileInputStream("E:/shw.jpg");
//创建字节输出流对象
fos=new FileOutputStream("E:/aa.jpg");
while((item=fis.read())!=-1){
fos.write(item);
}
//将数据从内存中写到磁盘上
fos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if (fis!=null){
try{
fis.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
FileInputStream fis=null;
int item=0;
FileOutputStream fos=null;
try{
//创建字节输入流对象
fis=new FileInputStream("E:/shw.jpg");
//创建字节输出流对象
fos=new FileOutputStream("E:/aa.jpg");
//创建一个缓冲区,提高读写效率
byte[] buff=new byte[1024];
while((item=fis.read(buff))!=-1){
fos.write(buff,0,item);
}
//将数据从内存中写到磁盘上
fos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if (fis!=null){
try{
fis.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
2.也是创建一个字节数组,不同的是相对于第一种方式是直接打包带走(第一种方式是分批次打包带走)通过流对象方法available()方法获得文件的预估长度 赋给数组长度 在一次读写操作中完成文件的读写,注意:如果文件过大,那么内存的占用也是比较大的!
public static void main(String[] args) {
FileInputStream fis=null;
int item=0;
FileOutputStream fos=null;
try{
//创建字节输入流对象
fis=new FileInputStream("E:/shw.jpg");
//创建字节输出流对象
fos=new FileOutputStream("E:/bb.jpg");
//创建一个缓冲区,提高读写效率
byte[] buff=new byte[fis.available()]; //通过流对象的available()方法返回对象的预估长度
fis.read(buff);
fos.write(buff);
//将数据从内存中写到磁盘上
fos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if (fis!=null){
try{
fis.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
Java中的字节缓冲流本身没有io流的读写功能,在别的流上加上缓冲功能提高效率,就像把别的流包装起来,因此缓冲流是一种处理流。
使用缓冲流就不需要自己定义缓冲区了,缓冲流中自带的有byte字节数组默认长度为8192,而且要注意关流的顺序
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
fis=new FileInputStream("D:/shw.jpg");
bis=new BufferedInputStream(fis);
fos=new FileOutputStream("D:/aa.jpg");
bos=new BufferedOutputStream(fos);
//缓冲流中的byte数组长度默认长度为8192
int temp=0;
while((temp=bis.read())!=-1){
bos.write(temp);
}
bos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
//注意:关闭流的顺序:“后开的先关”
if (bis!=null){
bis.close();
}
if (fis!=null){
fis.close();
}
if (bos!=null){
bos.close();
}
if (fos!=null){
fos.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
3.(上面是关于字节流)关于字符流跟字节流差不多 只不过缓冲区的数组变成了char类型数组 不能预估长度 而且关于字符流也有字符缓冲流 也是神似
BufferedReader br=null;
BufferedWriter bw=null;
try{
br=new BufferedReader(new FileReader(src));
bw=new BufferedWriter(new FileWriter(des));
String temp="";
while((temp=br.readLine())!=null){
bw.write(temp);
bw.newLine();
}
bw.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
}catch(Exception e){
e.printStackTrace();
}
}