1. 程式人生 > >java 將一張圖片拷貝到另外一個地方。(IO流)

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(); // 先開後關 } }