• [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();
                    }
                }
            }
        }
    }
  • 相关阅读:
    spring boot整合quartz存储到数据库
    java多线程定时器和java判断一个时间是否在时间区间内和用正则表达式获取String字符串之间的数据
    maven项目通过java加载mqtt存储到mysql数据库,实现发布和接收
    java往MongDB导入大量数据
    SSH面试题收藏
    Spring面试题
    Hibernate面试题收藏
    Spring MVC
    浅谈 Struts2 面试题收藏
    JSP 新闻发布会
  • 原文地址:https://www.cnblogs.com/zhengxl5566/p/10804085.html
Copyright © 2020-2023  润新知