【发布时间】:2019-08-29 07:15:23
【问题描述】:
所以我想问一下是否有任何方法可以修改我目前拥有的代码以使其仅替换文本文件的某些部分。 假设我有一个名为 TestFile1 的文本文件,其中包含
A = 苹果 B = 香蕉 C = 胡萝卜 D = 榴莲
还有一个叫做TestFile2,其中包含
A = 艺术 C = 蛤蜊
我想要发生的是代码应该能够比较两个文本文件,如果它发现有两个匹配的变量,那么 TestFile3 的输出文件将如下所示
A = 艺术 B = 香蕉 C = 蛤蜊 D = 榴莲
另外,我想让它动态化,这样我就不必每次更改变量时都更改代码,这样它就可以用于其他文本文件。
目前,我目前只有此代码,但它只是将 TestFile2 完全替换为 TestFile1,这不是我打算发生的。
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 中要求用户输入文件名的部分,因为我只是从我之前制作的程序中获取它,所以我需要的只是比较两个文件并生成输出按预期显示。任何帮助,将不胜感激。谢谢!
【问题讨论】:
标签: java file file-io text-files file-manipulation