Java IO流简单应用之文件Copy命令的实现
需求:
利用已学的java io完成dos中的copy命令,命令的格式为:Java Copy 源文件的完整路径 目标文件的完整路径
实现思路:
- 首先确定IO流的类型:因为文件可能不是文本文件,故选择字节流,然后选择读取和写入的方式,因为文件可能较大,故采用边读边写较好。
- 编写一个Cop类,利用主函数的两个参数分别获取待操作的文件路径,从而根据路径创建File对象,再根据创建的File对象分别创建FileInputStream对象和FileOutInputStream对象
- 通过创建的文件输入流和文件输出流对象循环读取写入数据,最后关闭输入输出流
具体实现代码:
//采用字节流边读边写复制文件
public class Copy {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("输入参数不正确");
System.out.println("正确格式为:java Copy 源文件路径 目标文件路径");
System.exit(1);
}
File f1 = new File(args[0]);
File f2 = new File(args[1]);
if(!f1.exists()){
System.out.println("源文件不存在");
System.exit(1);
}
InputStream input = null;
OutputStream out = null;
try {
input = new FileInputStream(f1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out = new FileOutputStream(f2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if(input!=null&&out!=null){
int temp = 0;
try{
while ((temp=input.read())!=-1){
out.write(temp);
}
System.out.println("文件复制成功");
}catch (IOException e){
e.printStackTrace();
System.out.println("文件复制失败");
}
try{
input.close();
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
注意:
在cmd中编译运行时,切换到当前Copy的包下,编译直接用Javac -encoding UTF-8 Copy.java即可,但使用java运行时,一定要返回上层目录(上层包中)然后用java packageName.Copy方可运行,不然提示找不到该类