java 实现txt文件的复制和追加

  • Post author:
  • Post category:java


题干(捏造):

实现输入

“源文件路径”

和“

要复制到的文件路径

”,对源文件判断,存在才能复制!对目标文件判断,不存在,则直接生成一个文件,若存在,则

询问追加还是覆盖

伪代码:

源文件 s1, 目标文件 s2

if (s1不存在){

提示要复制文件不存在

}elif (s2存在){

提示追加或者覆盖

}

难点(实力采坑)

BufferedReader fin = new BufferedReader(new FileReader(s1));

使用:

fin.readLine()

看似没问题,也确实没问题

不过,要

注意



fin.readLine() 每次调用,就默认行数加1!!

java 代码:

import java.io.*;
import java.util.Scanner;

public class lyy{
    static int n = 0;
    static void copy(DataInputStream fin,DataOutputStream fout) throws IOException {
        try {
        while(true) {
            fout.writeByte(fin.readByte());
        }
        }catch(EOFException e) {
            return;
        }
    }
    static void copy2(BufferedReader fin,PrintWriter fout) throws IOException {
        fout.println();
        fout.println();
        String str= null;
        while((str=fin.readLine()) != null)
        {
        System.out.println(str);    
        fout.println(str);
        }

        System.out.println("即将出入");
    }
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        String s1=s.nextLine(); //source root
        String s2 = s.nextLine(); //要复制到的文件

        File f1 = new File(s1);
        File f2 = new File(s2);

        if (!f1.exists()) {
            System.out.println("要复制的文件不存在");
            n = -1;
        }else if(f2.exists()) {
            System.out.println("要复制的文件已经存在,请选择1(覆盖源文件)或2(在源文件基础上追加):");
            n = s.nextInt();
            //System.out.println(n);
        }
            if (n==-1) {}
            else if((n == 0)||(n == 1)) {
                try {
                    DataOutputStream fout = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(s2)));
                    DataInputStream fin = new DataInputStream(new BufferedInputStream(new FileInputStream(s1)));

                    copy(fin,fout);
                    fin.close();fout.close();
                    System.out.println("复制完成,请及时查看");
                }catch (IOException e) {
                    System.out.println(e);
                }
            }else if(n == 2){
                try {
                    BufferedReader fin = new BufferedReader(new FileReader(s1));
                    PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter(s2,true)));

                    copy2(fin,fout);
                    fin.close();fout.close();

                    System.out.println("复制完成,请及时查看");
                }catch(IOException e) {
                    System.out.println(e);
                }
            }
    System.out.println("以结束");  
    }
}

使用方法

这里写图片描述

手工输入:

第一个路径:源文件路径

第二个路径:要复制的文件路径

最后两行为提示信息!



版权声明:本文为Inuyasha_1314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。