java 將一張圖片拷貝到另外一個地方。(IO流)


package com.beiwo.inputstream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class lianxi {

    /**
     * @param args
     * 練習題: 將一張圖片拷貝到另外一個地方。
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO 自動生成的方法存根
        String str1 = "C:\\Users\\cdlx2016\\Desktop\\1\\12字方針.png";
        String str2 = "C:\\Users\\cdlx2016\\Desktop\\2\\12字方針.png";
//        copyFile1(str1, str2);
//        copyFile2(str1, str2);
        copyFile3(str1, str2);
        
    }
    // 方法一
    public static void copyFile1(String srcPath, String destPath) throws IOException {
        // 打開輸入流
        FileInputStream fis = new FileInputStream(srcPath);
        // 打開輸出流
        FileOutputStream fos = new FileOutputStream(destPath);
        
        // 讀取和寫入信息
        int len = 0;
        while ((len = fis.read()) != -1) {
            fos.write(len);
        }
        
        // 關閉流  先開后關  后開先關
        fos.close(); // 后開先關
        fis.close(); // 先開后關
        
    }
    // 方法二
    public static void copyFile2(String srcPath, String destPath) throws IOException {
        
        // 打開輸入流
        FileInputStream fis = new FileInputStream(srcPath);
        // 打開輸出流
        FileOutputStream fos = new FileOutputStream(destPath);
        
        // 讀取和寫入信息
        int len = 0;
        // 創建一個字節數組,當做緩沖區
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            fos.write(b);
        }
        
        // 關閉流  先開后關  后開先關
        fos.close(); // 后開先關
        fis.close(); // 先開后關
        
    }
    // 方法三
    public static void copyFile3(String srcPath, String destPath) throws IOException {
        
        // 打開輸入流
        FileInputStream fis = new FileInputStream(srcPath);
        // 打開輸出流
        FileOutputStream fos = new FileOutputStream(destPath);
        
        // 讀取和寫入信息
        int len = 0;
        // 創建一個字節數組,當做緩沖區
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            fos.write(b, 0, len);
        }
        
        // 關閉流  先開后關  后開先關
        fos.close(); // 后開先關
        fis.close(); // 先開后關
        
    }

}

 


免責聲明!

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



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