要说java 的IO处理因为有了很多类看起来是很方便的,虽然都封装好了很多算法细节,但是如果只看JDK 文档的说明还是十分困惑的,比如说BufferedReader类里面的readLine()方法,刚开始的时候光看名字我一直以为是读取行可以间接读取的,其实是不可以间接读取的,在自写的实现类似功能的模仿类的时候,因为想实现异步的读取行操作所以做了很多无谓的工作,还是没办法写出来比较好的方法。
为什么很难写出来比较好的方法呢?
有一部分原因是基于这个IO系统本身的复杂性,如果说 C语言的话虽然很多功能需要自己算法实现,但是还算简单,如果你一开始莫名其妙的不知道该用哪个类的话,我觉得这是一点也不奇怪的,还有十分古怪的装饰模式,我认为这是个很好的东西,但是就我自己说的话还是太复杂了,不过这倒和java的庞大特性很符合,其实我一直在追求的是内在的东西,如果不去探索内在只是每天学别人的代码敲来敲去,我认为是完全没有意义的,所以我尽量让自己的小练习里面有点自己设计的东西在里面。
但是做的还是不太好,因为写的时候感觉不很自信,有没好设计,不过过度阶段还是难免的,先上程序吧。
我想考SCJP啊!上帝保佑!
/*
*20110830作业
*简单实现了一个文件复制的操作,目前设计不到位的地方是不可以复制目录,没有写嵌套复制操作,而且File 类不太好用
×实现目标目录建立的时候不好操作,具体使用方法见主方法
*另外对参数类型的判断也不是特别到位,以后改进
×Younger.shen 申延刚
×younger.x.shen@gmail.com
*blog: http://blog.youkuaiyun.com/hack2me
*/
import java.io.*;
public class CopyFileDemon{
private File source = null;
private File destination = null;
private FileInputStream fis = null;
private FileOutputStream fos = null;
private String destPath = null;
private byte[] buffer = new byte[1024*5];
public CopyFileDemon(String s , String dPath,String d){
source = new File(s);
destPath = dPath;
destination = new File(d);
}
private void copyFile(){
//int length = 0;
try{
fis = new FileInputStream(source);
//length = fis.available();
}catch(IOException e){
e.printStackTrace();
System.out.println("读取失败或文件不存在");
if(fis != null){
try{
fis.close();
}catch(IOException ex){
System.out.println("close file error");
}
}
System.exit(0);
}
try{
//System.out.println("fun");
if(!destination.exists()){
File temp = new File(destPath);
temp.mkdirs();
}
try{
fos = new FileOutputStream(destPath+destination.getName());
}catch(FileNotFoundException e){
System.out.println("创建文件失败,可能是由于目录名和文件名冲突,请重新尝试");
}
int c = 0;
long sum = 0;
while((c=fis.read(buffer))!=-1){
sum += c;
try{
fos.write(buffer, 0, c);
long length = source.length();
System.out.print((sum*100/length)+"%");
System.out.print( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
//System.out.println((int)(sum/length)+"%");
}catch(NullPointerException e){
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(fos!=null)
fos.close();
if(fis!=null)
fis.close();
}catch(IOException e){
System.out.println("close file error");
}
}
}
public static void main(String[] args){
if(args.length ==3){
CopyFileDemon index = new CopyFileDemon(args[0],args[1],args[2]);
index.copyFile();
}else{
System.out.println("请使用完全路径,第一个参数是原文件");
System.out.println("第二个参数是目标文件的目录 ");
System.out.println("第三个参数是目标文件名 ");
System.out.println("java CopyFileDemon c:/1.txt d:/ 2.txt ");
}
}
}