删除txt文件中的特定行然后复制到新的txt文件

时间:2021-04-10 13:16:57

标签: java file copy copy-paste txt

我在 java 中遇到了一些问题,我想将数字 5 删除到数字 7 并将它们保存到一个名为 RevisedNumbers.txt 的新文件中,有什么办法可以做到这一点?这是我目前的代码

import java.util.Scanner;
import java.io.*;
public class Txt {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
              File myObj = new File("Numbers1to10.txt");
              if (myObj.createNewFile()) {
                System.out.println("File created: " + myObj.getName());
              } else {
                System.out.println("File already exists.");
              }
            } catch (IOException e) {
              System.out.println("An error occurred.");
              e.printStackTrace();
            }
        
    try {
        Writer writer = new PrintWriter("Numbers1to10.txt");
        for(int i = 1; i <= 10; i++)
        {
            writer.write("Number" + i);
            writer.write("\r\n");
        }
        writer.close();
        File readFile = new File("Numbers1to10.txt");
        Scanner read = new Scanner(readFile);
        while (read.hasNextLine())
        System.out.println(read.nextLine());
    } catch (IOException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }
    
    try {
          File myObj = new File("RevisedNumbers.txt");
          if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
          } else {
            System.out.println("File already exists.");
          }
        } catch (IOException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }
}
}

新文件所需的输出为

Number 1
Number 2
Number 3
Number 4    
Number 8
Number 9
Number 10

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案可能是使用额外的文件。

在读取第一个文件(“Numbers1to10.txt”)的内容时,如果值在5到7之间,则将其写入第二个文件(“RevisedNumbers.txt”),否则将其写入附加文件。

现在附加文件包含您在第一个文件中需要的值。所以将附加文件的所有内容复制到第一个文件中。

这是一个示例代码。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileWriteMain {

    static void _write1to10(String locationWithFileName) {
        try {
            File file = new File(locationWithFileName);

            boolean fileAlreadyExist = file.exists();
            if (fileAlreadyExist) {
                System.out.println("File already exists!");
            } else {
                System.out.println("New file has been created.");
            }

            FileWriter fileWriter = new FileWriter(file);

            for (int i = 1; i <= 10; i++) {
                fileWriter.write("Number " + i);
                fileWriter.append('\n');
            }
            fileWriter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static File _getFile(String locationWithFileName) {
        File file = null;
        file = new File(locationWithFileName);
        return file;
    }

    // it reads a file and print it's content in console
    static void _readFile(Scanner scanner) {
        while (scanner.hasNextLine()) {
            String currLine = scanner.nextLine();
            System.out.println(currLine);
        }
    }

    // read contents from sourceFile file and copy it into destinationFile
    static void _copyFromOneFileToAnother(File sourceFile, File destinationFile) throws IOException {

        FileWriter destFileWriter = new FileWriter(destinationFile);

        Scanner scanner = new Scanner(sourceFile);
        while (scanner.hasNextLine()) {

            String currLine = scanner.nextLine();

            destFileWriter.write(currLine);
            destFileWriter.append('\n');
        }
        destFileWriter.close();

    }

    public static void main(String[] args) {

        String locationWithFileName = "E:\\FileWriteDemo\\src\\Numbers1to10.txt";   // give your file name including it's location
        _write1to10(locationWithFileName);

        System.out.println("File writing done!");

        File file1 = _getFile(locationWithFileName);
        try {

            // creating file 2
            String locationWithFileName2 = "E:\\FileWriteDemo\\src\\RevisedNumbers.txt";
            File file2 = _getFile(locationWithFileName2);
            FileWriter fileWriter2 = new FileWriter(file2);

            // creating a temporary file
            String tempFileLocationWithName = "E:\\FileWriteDemo\\src\\temporary.txt";
            File tempFile = _getFile(tempFileLocationWithName);
            FileWriter tempFileWriter = new FileWriter(tempFile);

            Scanner scanner = new Scanner(file1);

            while (scanner.hasNextLine()) {
                String currLine = scanner.nextLine();

                // split the word "Number" from integer
                String words[] = currLine.split(" ");

                for (int i = 0; i < words.length; i++) {
                    // System.out.println(words[i]);
                    try {
                        int num = Integer.parseInt(words[i]);

                        if (num >= 5 && num <= 7) {
                            // writing to second file

                            fileWriter2.write(currLine);
                            fileWriter2.append('\n');
                        } else {
                            // writing to temporary file

                            tempFileWriter.write(currLine);
                            tempFileWriter.append('\n');
                        }
                    } catch (NumberFormatException e) {
                        // current word is not an integer, so don't have to do anything
                    }
                }

            }
            fileWriter2.close();
            tempFileWriter.close();


            _copyFromOneFileToAnother(tempFile, file1);

            System.out.println("\nContents of first file");
            _readFile(new Scanner(file1));
            
            System.out.println("\nContents of second file");
            _readFile(new Scanner(file2));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

希望能帮到你!

快乐编码。

相关问题