zoukankan      html  css  js  c++  java
  • 利用字节流和字节数组流是实现文件的复制

    package ioxuexi;

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    /**
    * 利用字节流和字节数组流是实现文件的复制
    * @author User
    *
    */

    public class lianxi17 {
    public static void main(String[] args) throws IOException {
    byte[] data=get("E:/test/2.txt");
    set(data, "e:/test/45.txt");
    }
    //将目的字节数组放到目标区域
    public static void set(byte[] src,String destString) throws IOException{
    //创建目的文件源
    File destFile=new File(destString);
    //利用字节数组输入流录入字节数组
    InputStream isInputStream=new BufferedInputStream(new ByteArrayInputStream(src));
    //利用字节输出流输出文件
    OutputStream bosOutputStream=new BufferedOutputStream(new FileOutputStream(destFile));
    //进行操作
    byte[] flush=new byte[1024];
    int len=0;
    while (-1!=(len=isInputStream.read(flush))) {
    bosOutputStream.write(flush,0,len);
    }
    //强制刷出
    bosOutputStream.flush();
    //关闭文件流,释放资源
    isInputStream.close();
    bosOutputStream.close();

    }
    //通过字节流录入和字节数输出将源文件转换为字节数组
    public static byte[] get(String pathname) throws IOException {
    //创建文件源
    File srcFile=new File(pathname);
    byte[] dest=null;
    //利用字节输入流将目的地址的文件进行录入
    InputStream isInputStream=new BufferedInputStream(new FileInputStream(srcFile));
    //创建字节数组输出流
    ByteArrayOutputStream bosArrayOutputStream=new ByteArrayOutputStream();
    //进行字节数组录入
    byte[] flush=new byte[1024];
    int len=0;
    while (-1!=(len=isInputStream.read(flush))) {
    bosArrayOutputStream.write(flush,0,len);
    }
    bosArrayOutputStream.flush();
    //关闭文件流,释放资源
    isInputStream.close();
    bosArrayOutputStream.close();
    //返回一个字节数组
    return bosArrayOutputStream.toByteArray();

    }
    }

  • 相关阅读:
    Smobiler实现手机弹窗
    在 ASP.NET Web API 中使用 Attribute 统一处理异常
    VMWare的网络模式说明
    Windows Server2008 IIS通过Nginx实现绑定多个https域名
    Error while Launching activity
    Android 动态渐变按钮
    mysql安装和配置详解以及Navicat连接失败问题
    selenium的基础学习
    使用Pandas.read_csv时出现OSError: Initializing from file failed
    sklearn 机器学习 Pipeline 模板
  • 原文地址:https://www.cnblogs.com/zx931880423/p/6842962.html
Copyright © 2011-2022 走看看