java使用Inputstream和outputstream實現文件內容的拷貝,
package cn.ysc.cn;
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;
/**
* 文件拷貝
* 1.創建源
* 2.選擇流
* 3,操作
* 4/釋放資源
* @author Administrator
*
*/
public class TestIO_04_copy {
public static void main(String[] args) {
copy("abc.txt", "test.txt");
}
public static void copy(String srcPath,String destPath) {
//1.創建源
File src =new File(srcPath);//源頭
File test=new File(destPath);//源尾
//選擇流
InputStream is1=null;
OutputStream os1=null;
try {
is1=new FileInputStream(src);
os1=new FileOutputStream(test,true);
//3操作(分段讀寫)
byte[] flush=new byte[1024];//緩衝容器
int len =-1;//接收長度
while((len=is1.read(flush))!=-1) {
os1.write(flush,0,len);
}
os1.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (null!=os1) {
os1.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
try {
if (null!=is1) {
is1.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}