天天看點

InputStream、OutputStream應用--檔案複制

檔案複制功能實作: 指定一個檔案,将其複制到指定路徑下

public class copytxt190319 {
    public static void main(String[] args) throws IOException {
        //打開讀寫流,進行讀寫,關閉讀寫流
        String path = "C:\\Users\\a\\Desktop\\L\\inputtest.txt";
        String newpath = "C:\\Users\\a\\Desktop\\L\\i.txt";
        copyFile(path,newpath);
    }
    public static void copyFile(String srcPath,String destPath) throws IOException {
        //打開讀寫流
        FileInputStream is = new FileInputStream(srcPath);
        FileOutputStream os = new FileOutputStream(destPath);

        //進行讀寫
        int byt= 0;
        byte[] bytes = new byte[100];
        is.read();
        //讀法之一
        /*while ((byt = is.read()) != -1) {
            os.write(byt);
        }*/
        //讀法之二
        while ((byt = is.read(bytes)) != -1){
            os.write(bytes, 0, byt);
        }

        //錯誤執行個體  ==>資料讀取不完善
        while (is.read() != -1) {
            os.write(is.read());
        }

        //錯誤執行個體  ==>檔案大小受限
        is.read(bytes);
        os.write(bytes);


        //關閉讀寫流
        is.close();
        os.close();
    }
}