zoukankan      html  css  js  c++  java
  • [JAVA]使用字节流拷贝文件

    import java.io.*;
    
    /**
     * @Description:
     * @projectName:JavaTest
     * @see:PACKAGE_NAME
     * @author:郑晓龙
     * @createTime:2019/5/3 0:45
     * @version:1.0
     */
    public class CopyWithBytes {
        public static void main(String[] args) {
            byte[] bytes = readFileToByteArray("d:/abc.txt");
            writeByteArrayToFile(bytes,"d:/23123.txt");
        }
    
        public static byte[] readFileToByteArray(String src) {
            // 文件输入流(需要关闭)
            InputStream is = null;
            try {
                is = new FileInputStream(new File(src));
                // 字节数组输出流(不需要关闭)
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024 * 1];
                int len;
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return baos.toByteArray();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    
        public static void writeByteArrayToFile(byte[] datas, String destFileName) {
            // 文件输出流(需要关闭)
            OutputStream os = null;
            try {
                // 字节数组输入流(不需要关闭)
                InputStream is = new ByteArrayInputStream(datas);
                os = new FileOutputStream(new File(destFileName));
    
                byte[] buf = new byte[1024];
                int len;
                while (((len = is.read(buf)) != -1)) {
                    os.write(buf, 0, len);
                }
                os.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
  • 相关阅读:
    yii2.0 干货
    VLD opcodes 在线查看
    定长顺序串的实现
    循环队列
    oracle--DG初始化参数
    oracle --工具 ODU
    Oracle RAC 修改SPFILE路径 文件查看
    oracle 错误 ORA-00020问题解析
    oracle 错误 TNS-01190与oracle 登入没反应操作
    Oracle--RMAN Recover 缺失的归档操作
  • 原文地址:https://www.cnblogs.com/zhengxl5566/p/10804085.html
Copyright © 2011-2022 走看看