该文章在https://blog.csdn.net/xyphf/article/details/78276796这个博客中修改的,如有侵权,请告知!
在上述博客中添加了一点简单的判断:
源文件是否存在,指定目录是否存在,判断新文件是否重复。
接下来是代码:
package libao;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class CopyFileDemo {
public static void main(String[] args) {
// 将F盘下面的file.txt文件拷贝到桌面
Scanner scanner = new Scanner(System.in);
System.out.println("请输入源文件:");
String srcPathStr = scanner.next(); // 源文件地址
File oldfile = new File(srcPathStr);
if (!oldfile.exists() || !oldfile.isFile()) { //判断源文件是否存在
System.out.println("该文件不存在或文件错误");
} else {
System.out.println("请输入新目录:");
String desPathStr = scanner.next(); // 目标文件地址
String newDesPathStr = new String(desPathStr); //用于判断新文件是否存在于指定目录中
File newfile = new File(desPathStr);
String newFileName = srcPathStr.substring(srcPathStr.lastIndexOf("/") + 1); // 文件名称
newDesPathStr = newDesPathStr + File.separator + newFileName; // 新文件地址及名称
File desfile = new File(newDesPathStr);
System.out.println(newfile);
if (!newfile.isDirectory() || !newfile.exists()) { // 判断文件目录是否存在
System.out.println("该路径不是目录或路径错误");
}else if(desfile.exists()){ //如果存在
System.out.println("该文件已存在!");
}else { //执行传输
copyFile(srcPathStr, desPathStr);
if(desfile.exists()) {
System.out.println("传输成功!");
}
}
}
}
/*
* 实现文件的拷贝
*
* @param srcPathStr 源文件的地址信息
*
* @param desPathStr 目标文件的地址信息
*/
private static void copyFile(String srcPathStr, String desPathStr) {
// 1.获取源文件的名称
String newFileName = srcPathStr.substring(srcPathStr.lastIndexOf("/") + 1); // 目标文件地址
System.out.println("123"+newFileName);
desPathStr = desPathStr + File.separator + newFileName; // 源文件地址
System.out.println("1234"+desPathStr);
try {
// 2.创建输入输出流对象
FileInputStream fis = new FileInputStream(srcPathStr);
FileOutputStream fos = new FileOutputStream(desPathStr);
// 创建搬运工具
byte datas[] = new byte[1024 * 8];
// 创建长度
int len = 0;
// 循环读取数据
while ((len = fis.read(datas)) != -1) {
fos.write(datas, 0, len);
}
// 3.释放资源
fis.close();
fis.close();
} catch (Exception e) {
System.out.println("错误");
}
}
}