當前位置:
首頁 >
FileInputStream和FileOutputStream实现任何文件类型的拷贝
發布時間:2025/3/21
47
豆豆
生活随笔
收集整理的這篇文章主要介紹了
FileInputStream和FileOutputStream实现任何文件类型的拷贝
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 文件拷貝
- 實現代碼
- 再次強調
- 運行截圖
- 運行前
- 運行后
文件拷貝
表示如下圖:
實現代碼
package Filecopy01;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;/* * 使用FileInputStream +FileOutputStream完成文件的拷貝 * 拷貝的過程應該是一邊讀,一邊寫 * 使用以上字節流拷貝文件時,文件類型隨意,萬能的 * */ public class Copy01 {public static void main(String[] args) {FileInputStream fis=null;FileOutputStream fos=null;try {fis=new FileInputStream("D:\\01.png");fos=new FileOutputStream("E:\\02.png");//最核心的:一邊讀,一邊寫byte[]bytes=new byte[1024*1024];//(一次拷貝1MB)int readCount=0;while((readCount=fis.read(bytes))!=-1){fos.write(bytes,0,readCount);}//刷新,輸出流要刷新fos.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//分開try,不能一起try//一起try的時候,其中一個 出現異常,可能會影響另一個流的關閉if(fis!=null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}if(fos!=null){try {fos.close();} catch (IOException e) {e.printStackTrace();}}}} }再次強調
運行截圖
運行前
運行后
大小一模一樣 ,也可以換成視頻這些來拷貝
總結
以上是生活随笔為你收集整理的FileInputStream和FileOutputStream实现任何文件类型的拷贝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA_IO流四大家族(1)
- 下一篇: JAVA_IO流四大家族(2)