代码:
package main.java.java02.IO;
import java.io.*;
/**
* @author:Mr.wang
* @date:2019/2/21 0021 上午 10:00
*/
public class fuzhiwenjian02 {
public static void main(String args[]) {
//选择文件
File src=new File("d:/a/a.txt");
File dest=new File("d:/a/b.txt");
//选择流
try {
InputStream is=new FileInputStream(src);
OutputStream os=new FileOutputStream(dest);
//拷贝 循环+读取+写出
byte[]flush=new byte[1024];
int len=0;
//读取
while(-1!=(len=is.read(flush))){
//写出
os.write(flush,0,len);
}
os.flush();//强制刷出
//关闭流 先打开后关闭
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
提取方法,之后直接使用:
public class fuzhiwenjian02 {
public static void main(String args[]) {
String src="d:/a/a.txt";
String dest="d:/a/b.txt";
copyFile(src,dest);
}
//提取方法
public static void copyFile(String srcPath, String destPath) throws IOException {
File src=new File(srcPath);
File dest=new File(destPath);
//选择流
try {
InputStream is=new FileInputStream(src);
OutputStream os=new FileOutputStream(dest);
//拷贝 循环+读取+写出
byte[]flush=new byte[1024];
int len=0;
//读取
while(-1!=(len=is.read(flush))){
//写出
os.write(flush,0,len);
}
os.flush();//强制刷出
//关闭流 先打开后关闭
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
优化:
package main.java.java02.IO;
import java.io.*;
/**
* @author:Mr.wang
* @date:2019/2/21 0021 上午 10:00
*/
public class fuzhiwenjian02 {
public static void main(String args[]) {
String src = "d:/a/a.txt";
String dest = "d:/a/b.txt";
try {
copyFile(src, dest);
}
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
}catch (IOException e){
e.printStackTrace();
System.out.println("拷贝失败!");
}
}
//整理方法
public static void copyFile(String srcPath, String destPath) throws IOException {
File src=new File(srcPath);
File dest=new File(destPath);
if(!src.isFile()){
System.out.println("只能拷贝文件!");
return;
}
//选择流
InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(dest);
//拷贝 循环+读取+写出
byte[] flush = new byte[1024];
int len = 0;
//读取
while (-1 != (len = is.read(flush))) {
//写出
os.write(flush, 0, len);
}
os.flush();//强制刷出
//关闭流 先打开后关闭
os.close();
is.close();
}
}