java實現簡單的IO字節流讀寫操作

package com.yang.stream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileDemo {
    public static void main(String[] args) {
        String oldpath = "d:/a.txt";
        String newpath = "d:/b.txt";
        BufferedInputStream in = null;
        BufferedOutputStream os = null;
        try {
            in = new BufferedInputStream(new FileInputStream(new File(oldpath)));
            os = new BufferedOutputStream(new FileOutputStream(new File(newpath)));
            byte[] b = new byte[1024];
            int len = 0;
            while((len=in.read(b))!=-1){
                os.write(b, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
        } catch (IOException e) {
            System.out.println("輸入輸出異常");
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("文件傳輸成功");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章