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、建立联系 File 对象 源头 目的地
* 2、选择流 既然是文件的拷贝 那肯定包含了 读取跟写入 所以
* 1)文件输入流 InputStream FileInputStream
* 2)文件输出流 OutputStream FileOutputStream
* 3、操作:拷贝 -->一边读取 一边写入 就可以完成拷贝了
* byte flush[] = new byte[1024];
* int len = 0;
* while(-1=(len=输入流.read(flush))){
* 输出流.write(flush,0,len);
* }
* 输出流.flush;
* 4、释放资源:关闭两个流
*/
public class Demo01 {
public static void main(String[] args){
String str = new String("e:/work/a.txt");
String str1 = new String("e:/work/asdfg.txt");
try {
copyFile(str, str1);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件未找到!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件拷贝失败!没事找找bug再来!!!");
}
}
public static void copyFile(String srcPath,String datePath) throws FileNotFoundException,IOException{
//源文件 必须是文件不能是文件夹 输入流是读取不了文件夹的
File src = new File(srcPath);
//目的地 文件可以不存在
File date = new File(datePath);
//打开流
InputStream it = new FileInputStream(src);
OutputStream os = new FileOutputStream(date);
//文件拷贝
byte flush[] = new byte[1024];
int len = 0;
while(0<=(len=it.read(flush))){
os.write(flush, 0, len);
}
//关闭流的注意 先打开的后关
os.close();
it.close();
}
}
运用InputStream和OutputStream写个简单的拷贝文件
最新推荐文章于 2024-08-28 19:51:46 发布