- /**
- * 复制文件
- * 运行命令行 java CopyFile C:/1.txt D:1.txt
- * */
- import java.io.*;
- import java.text.*;
- import java.util.*;
- public class CopyFile {
- public static void main(String[] args) throws IOException {
- new CopyFile().copy(args[0], args[1], Integer.parseInt(args[2]));
- }
- public int copy(String source_name, String dest_name, int type)
- throws IOException {
- File source_file = new File(source_name);
- File dest_file = new File(dest_name);
- FileInputStream source = null;
- FileOutputStream destination = null;
- byte[] buffer;
- int bytes_read;
- int result = 0;
- try {
- if (!source_file.exists() || !source_file.isFile())
- throw new RuntimeException("FileCopy: no such source file: "
- + source_name);// 源文件不存在
- if (!source_file.canRead())
- throw new RuntimeException("FileCopy: source file "
- + "is unreadable: " + source_name);// 源文件不可读
- if (dest_file.exists()) {
- if (dest_file.isFile()) {
- if (type == 1) // 覆盖
- {
- dest_file.delete();
- result = 1;
- } else // 不覆盖
- {
- result = 2;
- return result;
- }
- } else
- throw new RuntimeException("FileCopy: destination "
- + "is not a file: " + dest_name);// 目标是目录而不是文件
- } else {
- File parentdir = new File(dest_file.getParent());
- if (!parentdir.exists())
- throw new RuntimeException("FileCopy: destination "
- + "directory doesn't exist: " + dest_name);// 目标路径不存在
- if (!parentdir.canWrite())
- throw new RuntimeException("FileCopy: destination "
- + "directory is unwriteable: " + dest_name);// 目标路径不可写
- }
- // 复制文件
- source = new FileInputStream(source_file);
- destination = new FileOutputStream(dest_file);
- buffer = new byte[1024];
- while (true) {
- bytes_read = source.read(buffer);
- if (bytes_read == -1) {
- break;
- }
- destination.write(buffer, 0, bytes_read);
- }
- } finally {
- if (source != null) {
- try {
- source.close();
- } catch (IOException e) {
- }
- }
- if (destination != null) {
- try {
- destination.close();
- } catch (IOException e) {
- }
- }
- return result;
- }
- }
JDK6.0学习笔记(六)复制文件
最新推荐文章于 2021-03-19 18:32:58 发布