文件内容复制

package FileIO;
import java.io.*;
import java.util.*;
public class CopyFileDemo {

public static void main(String[] args) {
File source=new File("demo.txt");
File objfile=new File("objfile.txt");
int b;
Scanner scan=new Scanner(System.in);
System.out.println("选择读取方式(字符数组读取为0,字符读取为1:)");
b=scan.nextInt();
if(b==1){
Copy1(source,objfile);
}
else{
Copy2(source,objfile);
}
}

//读一个字符复制一个
public static void Copy1(File source,File objfile){
FileReader fr = null;
    FileWriter fw = null;
    try {
           // 声明读,写流对象
           fr = new FileReader(source);
           fw = new FileWriter(objfile,true);
           int ch = 0;
           int count=0;
           // 开始读
           while ((ch = fr.read()) != -1) {
               count++;
               System.out.println("正在读取"+count+"行");
               fw.write(ch);
               fw.write("\r\n"); //换行
               System.out.println("正在写入"+count+"行");
           }
           System.out.println("读写完成");
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {


           try {
               if (fw != null)
                   fw.close();


           } catch (IOException e) {
               e.printStackTrace();
           }
           try {
               if (fr != null)
                   fr.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }


   }

//数组方式读取复制
public static void Copy2(File source,File objfile){
FileReader fr=null;
FileWriter fw=null;

try{
//声明读,写流对象
fr=new FileReader(source);
fw=new FileWriter(objfile,true);
int ch=0;
int count=0;
char[]buf=new char[1024];
//开始读
while((ch=fr.read(buf))!=-1){
count++;
System.out.println("正在读取"+count+"行");
fw.write(buf,0,ch);
fw.write("\r\n");//换行
System.out.println("正在写入"+count+"行");
}
System.out.println("读写完成!");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(fw!=null){
try{
fw.close();
}catch(IOException e){
e.printStackTrace();
}
if(fr!=null){
try{
fr.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值