黑马程序员技术交流社区
标题:
io
[打印本页]
作者:
fmi110
时间:
2015-9-8 16:03
标题:
io
s
/**
* 需求:复制文本文件
* 分析: 1 文本属于字符流
* 2 需要给出源文本文件,和目标文件
*/
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class TxtCopy {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入源文件的完整路径:");
String srcPath = new Scanner(System.in).nextLine();
System.out.println("请输入目标文件的完整路径:");
String desPath = new Scanner(System.in).nextLine();
try{
// copy1(srcPath,desPath);
copy2(srcPath,desPath);
}catch(IOException e){
e.printStackTrace();
}
}
private static void copy2(String srcPath, String desPath) throws IOException {
// TODO Auto-generated method stub
File srcfile = new File(srcPath);
if(!srcfile.exists()){
System.out.println("输入源文件地址错误,找不到文件!!");
return ;
}
BufferedReader fr = new BufferedReader(new FileReader(srcfile));
//建立目标文件,并检测是否存在,若存在 提示覆盖还是合并
File desfile = new File(desPath);
String flag1 = null;//记录覆盖操作的选择
int flag = -1;
if(desfile.exists()){
System.out.println("文件已存在,是否进行合并? 0:否 1 是");
flag1 = new Scanner(System.in).nextLine();
flag = Integer.parseInt(flag1);
}
BufferedWriter fw = null;
switch(flag){
case 0:
fw = new BufferedWriter(new FileWriter(desPath));
break;
case 1:
fw = new BufferedWriter(new FileWriter(desPath,true));
break;
default:
}
String line = null;
while((line = fr.readLine())!=null){
fw.write(line);
fw.newLine();
fw.flush();
}
fr.close();
fw.close();
System.out.println("copy done!");
}
private static void copy1(String srcPath, String desPath)
throws IOException {
// TODO Auto-generated method stub
//建立抽象源文件和目标文件
File srcfile = new File(srcPath);
if(!srcfile.exists()){
System.out.println("输入源文件地址错误,找不到文件!!");
return ;
}
FileReader fr = new FileReader(srcfile);
//建立目标文件,并检测是否存在,若存在 提示覆盖还是合并
File desfile = new File(desPath);
String flag1 = null;//记录覆盖操作的选择
int flag = -1;
if(desfile.exists()){
System.out.println("文件已存在,是否进行合并? 0:否 1 是");
flag1 = new Scanner(System.in).nextLine();
flag = Integer.parseInt(flag1);
}
FileWriter fw = null;
switch(flag){
case 0:
System.out.println("请重新输入名字:");
desPath = new Scanner(System.in).nextLine();
fw = new FileWriter(desPath);
break;
case 1:
fw = new FileWriter(desPath,true);
break;
default:
fw = new FileWriter(desPath,true);
}
int by = 0;
while((by = fr.read())!= -1){
fw.write(by);
}
//关闭资源
fr.close();
fw.close();
System.out.println("copy done!!");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2