java完成图片的复制,要求1、请用户输入图片的源路径(提示用\\);判断图片是否存在,如果不存在,要求用户重新输入;2、要求用户输入日的目录,判断是否是一个文件,如果不是文件,在日的路径后加上文件名;
时间: 2024-03-26 15:41:26 浏览: 11
好的,针对您的问题,我可以给出以下Java代码示例来实现图片的复制:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Scanner;
public class ImageCopy {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. 输入图片源路径
System.out.print("请输入图片的源路径(格式如:D:\\\\images\\\\test.jpg):");
String srcPath = scanner.nextLine();
// 判断图片是否存在,如果不存在,要求用户重新输入
File srcFile = new File(srcPath);
while (!srcFile.exists()) {
System.out.print("图片不存在,请重新输入图片的源路径(格式如:D:\\\\images\\\\test.jpg):");
srcPath = scanner.nextLine();
srcFile = new File(srcPath);
}
// 2. 输入目标路径
System.out.print("请输入目标路径(格式如:D:\\\\backup\\\\):");
String destPath = scanner.nextLine();
// 判断目标路径是否是一个文件,如果不是文件,在目标路径后加上文件名
File destFile = new File(destPath);
if (destFile.isFile()) {
destPath = destFile.getParent() + File.separator;
}
// 执行图片复制操作
try {
FileChannel srcChannel = new FileInputStream(srcFile).getChannel();
FileChannel destChannel = new FileOutputStream(destPath + srcFile.getName()).getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
destChannel.close();
System.out.println("图片复制成功!");
} catch (IOException e) {
System.out.println("图片复制失败:" + e.getMessage());
}
}
}
```
上述代码中,通过Scanner类实现用户输入图片源路径和目标路径,然后通过File类判断图片是否存在以及目标路径是否是一个文件。最后使用FileChannel类实现图片的复制操作。