首頁  >  文章  >  Java  >  Java中使用IO流複製檔案的方法實例解析

Java中使用IO流複製檔案的方法實例解析

PHPz
PHPz轉載
2023-04-24 12:40:071607瀏覽

1、使用FileInputStream、FileOutputStream完成檔案的複製

    public void fileCapy(String src, String dest) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
 
        try {
            fis = new FileInputStream(new File(src));
            fos = new FileOutputStream(new File(dest));
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2、使用FileReader、 FileWriter完成文字的複製(對於非文字檔案, 只能使用位元組流)

    public void textCapy(String src, String dest) {
        FileReader fr = null;
        FileWriter fw = null;
 
        try {
            fr = new FileReader(new File(src));
            fw = new FileWriter(new File(dest));
            char[] chars = new char[1024];
            int length;
            while ((length = fr.read(chars)) != -1) {
                fw.write(chars, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

以上是Java中使用IO流複製檔案的方法實例解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除