现在的位置: 首页 > 综合 > 正文

IO操作的一个例子(copy文件的命令)

2013年10月21日 ⁄ 综合 ⁄ 共 1565字 ⁄ 字号 评论关闭

使用IO操作完成一个文件的拷贝功能,默认dos中的copy命令: java copy 源文件  目标文件

本程序使用边读边写的方法

目前出现问题: 在复制完成后 点击停止按钮 会出现 exception in thread main  异常

下面是代码 请知道原因的同学帮我纠正一下 在此感激万分

package com.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class JavaCopyDemo {
	public static void main(String[] args) throws Exception{
		System.out.println("拷贝文件的命令 java copy 源文件路径  目标文件路径");
		System.out.println("————————————————————————————————————————————");
		System.out.println("请输入命令:");
		Scanner scanner = new Scanner(System.in);
		boolean isCanScanner = true;
		while(isCanScanner){
			String code = scanner.nextLine();
			if(code.equals("quit")){
				break;
			}else{
				String[] codeContents = code.trim().split("\\s+");
				if(codeContents.length>0&&(!("".equals(code.trim())))){
					if(codeContents.length==4){
						if(codeContents[0].equals("java")&&codeContents[1].equals("copy")){
							copy(codeContents[2], codeContents[3]);
						}else{
							System.out.println("请输入有效命令");
						}
					}else{
						System.out.println("请输入有效命令");
					}
				}
			}
		}

	}

	public static void copy(String fileName1,String fileName2) throws IOException{
		if(fileName1.equals(fileName2)){
			System.out.println("文件无法自身赋值");
		}else{
			File file1 = new File(fileName1);
			File file2 = new File(fileName2);
			if(!file1.exists()){
				System.out.println("要复制的文件不存在。。");
			}else{
				InputStream inputStream = new FileInputStream(file1);
				OutputStream outputStream = new FileOutputStream(file2);
				//定义一个整数表示接收的内容
				int temp = 0; 
				while((temp=inputStream.read())!=-1){//表示内容还可以继续读
					outputStream.write(temp);
				}
				System.out.println("复制成功"+file2.getAbsolutePath());
				inputStream.close();
				outputStream.close();
				
			}
		}
	}
}


抱歉!评论已关闭.