gpt4 book ai didi

Java程序比较两个文本文件,然后将第一个文本文件中找到的变量替换为第二个文件中的变量到第三个文件中

转载 作者:行者123 更新时间:2023-12-02 01:09:22 25 4
gpt4 key购买 nike

所以我想问是否有任何方法可以修改我当前拥有的代码,使其仅替换文本文件的某些部分。假设我有一个名为 TestFile1 的文本文件,其中包含

A = Apple B = Banana C = Carrot D = Durian

另一个名为 TestFile2,其中包含

A = Art C = Clams

我希望发生的是代码应该能够比较两个文本文件,如果发现有两个匹配的变量,则输出文件 TestFile3 将如下所示

A = Art B = Banana C = Clams D = Durian

此外,我想使其动态化,这样我就不必每次更改变量时都更改代码,以便它可以用于其他文本文件。

目前,我只有这段代码,但它的作用只是完全用 TestFile1 完全替换 TestFile2,这不是我想要发生的事情。

import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.charset.Charset;
import java.io.*;
import java.util.Scanner;

public class FindAndReplaceTest {

static void replaceTextFile(String fileName, String target, String replacement, String toFileName) throws IOException
{
Path path = Paths.get(fileName);
Path toPath = Paths.get(toFileName);
Charset charset = Charset.forName("UTF-8");
BufferedWriter writer = Files.newBufferedWriter(toPath, charset);
Scanner scanner = new Scanner(path, charset.name());
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
line = line.replaceAll(target, replacement);
writer.write(line);
writer.newLine();
}
scanner.close();
writer.close();
}

public static void main(String[] args) throws IOException{
replaceTextFile("C:\\Users\\LS1-10\\Documents\\TestFile2.txt", "Write", "Read", "C:\\Users\\LS1-10\\Documents\\TestFile1.txt");
/*
System.out.println("Note: Make sure files to merge are in the same directory as this program!");
Scanner in = new Scanner(System.in);
String output, file1name, file2name;
System.out.print("Enter output file name: ");
output = in.nextLine();
PrintWriter pw = new PrintWriter(output + ".txt");

System.out.print("Enter name of first file: ");
file1name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader(file1name + ".txt"));
String line = br.readLine();

System.out.print("Enter name of second file: ");
file2name = in.nextLine();
br = new BufferedReader(new FileReader(file2name + ".txt"));

line = br.readLine();

pw.flush();

br.close();
pw.close();

System.out.println("Replaced variables in " + file1name + ".txt with variables in " + file2name + ".txt into " + output + ".txt"); */
}
}

我注释掉了 psvm 中要求用户输入文件名的部分,因为我只是从我之前制作的程序中获取了它,所以我需要的只是比较两个文件并制作输出按预期显示。任何帮助,将不胜感激。谢谢!

最佳答案

考虑到所有内容都适合内存,最优雅的方法是:

  1. 将 file2 反序列化为 map
  2. 读取 file1 时,检查该变量在映射中是否有关联值,并在输出到 file3 之前根据需要进行替换。

关于Java程序比较两个文本文件,然后将第一个文本文件中找到的变量替换为第二个文件中的变量到第三个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com