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();

    }
    }

  • 相关阅读:
    sublime text3快速编辑选中多行
    sublime text3实现多行快速编辑Ctrl+E或者Tab
    WPF集合控件实现分隔符(ItemsControl Separator)
    WPF的ListView控件自定义布局用法实例
    ASP.NET MVC4+BootStrap 实战(一)
    wpf 获取datagrid 模板列中的控件
    WPF之DataGrid篇:DataGridComboBoxColumn
    WPF DataGrid 样式分享
    WPF之DataTemplateSelector技巧
    【WPF】ComboBox:根据绑定选取、设置固定集合中的值
  • 原文地址:https://www.cnblogs.com/zx931880423/p/6842962.html
Copyright © 2011-2022 走看看