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

假如需要复制一张图片,一份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,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,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为转换流,前者将字节流转化为字符流,后者将字符流转化为字节流

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

相关文章

本文从从Bitcask存储模型讲起,谈轻量级KV系统设计与实现。从...
内部的放到gitlab pages的博客,需要统计PV,不蒜子不能准确...
PCM 自然界中的声音非常复杂,波形极其复杂,通常我们采用的...
本文介绍如何离线生成sst并在线加载,提供一种用rocksdb建立...
验证用户输入是否正确是我们应用程序中的常见功能。Spring提...
引入pdf2dom &lt;dependency&gt; &lt;groupId&a...