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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM