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(); } } } } }
原文地址:https://www.cnblogs.com/zhengxl5566/p/10804085.html
时间: 2024-10-16 21:53:23