IO流拷貝圖片的四種方式
阿新 • • 發佈:2019-01-11
package IO; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyImg { /** * * IO流複製圖片(記事本開啟不能讀懂),使用位元組流 * 4種方式,推薦使用第四種 * */ public static void main(String[] args) throws IOException { //資料來源 File srcfile=new File("資料來源"); //目的地 File destfile=new File("目的地"); //methd1(srcfile,destfile); //methd2(srcfile,destfile); //methd3(srcfile,destfile); methd4(srcfile,destfile); } //方式四:緩衝位元組流一次讀寫一個位元組陣列 private static void methd4(File srcfile, File destfile) throws IOException { BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcfile)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destfile)); byte[] by=new byte[1024]; int length=0; while((length=bis.read(by))!=-1){ bos.write(by,0,length); } //關閉資源 bos.close(); bis.close(); } /* //方式三:緩衝位元組流一次讀寫一個位元組 private static void methd3(File srcfile, File destfile) throws IOException { BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcfile)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destfile)); int by=0; while((by=bis.read())!=-1){ bos.write(by); } bos.close(); bis.close(); } */ /* //方式二:基本位元組流一次讀寫一個位元組陣列 private static void methd2(File srcfile, File destfile) throws IOException { FileInputStream fis=new FileInputStream(srcfile); FileOutputStream fos=new FileOutputStream(destfile); byte[] by=new byte[1024]; int length=0; while((length=fis.read(by))!=-1){ fos.write(by,0,length); } fos.close(); fis.close(); } */ /* //方式一:基本位元組流一次讀寫一個位元組 private static void methd1(File srcfile, File destfile) throws IOException { FileInputStream fis=new FileInputStream(srcfile); FileOutputStream fos=new FileOutputStream(destfile); int by=0; while((by=fis.read())!=-1){ fos.write(by); } fos.close(); fis.close(); } */ }