天天看點

Java:用Inputstream和Outputstream來複制檔案

Java:用Inputstream和Outputstream來複制檔案

在學了io流後,用Inputstream和Outputstream編了一個Copy檔案的代碼

可以用來複制任何類型的檔案。差別另一篇檔案字元流隻能用來複制字元檔案。

package com.mjd.io;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

public class TestCopy {

public static void main(String[] args) {

Copy(“image.jpg”,“imageCopy.jpg”);//調用Copy方法

}

public static void Copy(String srcPath,String destPath) { //構造Copy方法

File src =new File(srcPath);

File dest =new File(destPath);

InputStream is=null;

OutputStream os=null;

try {

is =new FileInputStream(src);

os =new FileOutputStream(dest);

byte flush[] =new byte [1024];

int len =-1;

try {

while((len=is.read(flush))!=-1) {

os.write(flush,0,len);

}

os.flush();

} catch (IOException e) {

e.printStackTrace();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}finally {

if(null!=os) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(null!=is) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

Java:用Inputstream和Outputstream來複制檔案