程序使用文件输入输出流,实现对文件复制,美中不足:无法对中文字符进行复制,会导致乱码,好像是字节读入那里有点小问题,以后本事大了再回来修改,残缺品自己保存。。。dalao看不见我,看不见我~
package unit2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;public class FileCopy {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
while(true) {
System.out.println("请输入:-----源文件名------目的文件名");
Scanner sc=new Scanner(System.in);
String source=sc.next(); //源文件名
String direct=sc.next(); //目的文件名
String path="F:/workspace_eclipse/unit1/ "; //粘贴路径
sc.close();
File sourceFileName=new File(source); //创建源文件
sourceFileName.createNewFile();
File directionFileName=new File(path.concat(direct));//创建目的文件
directionFileName.createNewFile();
String result = null;
System.out.println("源文件的路径:"+sourceFileName.getAbsolutePath());
if(!sourceFileName.exists()) {
sourceFileName.createNewFile();
System.out.println("未发现该文件,已经创建新文件!请输入您要在新文件中添加什么内容:");
Scanner st=new Scanner(System.in);
FileOutputStream out=new FileOutputStream(sourceFileName);
@SuppressWarnings("unused")
String contents=st.next();
byte[] bu=new byte[1024];
out.write(bu);
out.close();
st.close();
}
else {
System.out.println("已经找到源文件,正在进行复制操作,请等待......");
}
FileReader fr;
if(sourceFileName.length()==0) {
System.out.println("已经成功复制,请根据以下路径寻找对应文件:"+directionFileName.getCanonicalFile());
}
else {
fr=new FileReader(sourceFileName);
char[] cb=new char[9999999];
int hasread=-1;
while((hasread=fr.read(cb))!=-1){
result=new String(cb,0,hasread);
}
FileWriter fw;
String temp=result;
fw=new FileWriter(directionFileName,true);
fw.write(temp, 0, temp.length());
fw.close();
System.out.println("已经成功复制,请根据以下路径寻找对应文件:"+directionFileName.getCanonicalFile());
}
}
}
}
运行结果如下: