我有一个文件(FILE1.TXT)包含:
word word word2 word word1
word2 word word 1
其他文件(FILE2.TXT)包含:
word1-replacement1
word2-replacement2
我需要一个查找方法,如果从文件2的话中包含的文件1,以及它们是否包含与替换替换那些话。 我已经有以下几点:
BufferedReader br = new BufferedReader(new FileReader("file2.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("file1.txt"));
String line;
String line2;
while ((line = br.readLine()) != null) {
String vars[] = line.split("-");
String varname = vars[0];
String replacement = vars[1];
while ((line2 = br2.readLine()) != null) {
if(line2.contains(varname)) {
line2.replace(varname, replacement);
}
}
}
这段代码的问题是,它只是只读取文件1的第一道防线。 最终的输出应该是这样的:
word word replacement2 word replacement1
replacement2 word replacement1
谢谢你的帮助 :)
我建议先读第二个文件到Java的内存和存储的数据作为HashMap中的键值存储。然后,遍历从第一个文件中的行,并进行匹配替换。
Map<String, String> map = new HashMap<>();
String line = "";
try (BufferedReader br = new BufferedReader(new FileReader("file2.txt"))) {
while ((line = br.readLine()) != null) {
String[] parts = line.split("-");
map.put(parts[0], parts[1]);
}
}
catch (IOException e) {
// handle exception
}
try (BufferedReader br = new BufferedReader(new FileReader("file1.txt"))) {
while ((line = br.readLine()) != null) {
for (Map.Entry< String, String > entry : map.entrySet()) {
String pattern = "\\b" + entry.getKey() + "\\b";
line = line.replaceAll(pattern, entry.getValue());
// now record the updated line; printed to the console here for demo purposes
System.out.println(line);
}
}
}
catch (IOException e) {
// handle exception
}
请注意,这里我称之为String#replaceAll
上面围绕每学期单词边界。这一点很重要,因为,例如,无国界的术语word1
将匹配类似aword1term
,也就是说,它将匹配word1
甚至其他的一些单词的字符串。
您可以通过创建一个地图像这样的替换的开始:
public Map<String,String> getReplacements(File file) throws FileNotFoundException {
Map<String, String> replacementMap = new HashMap<>();
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
String line = sc.nextLine();
String [] replacement = line.split("-");
String from = replacement[0];
String to = replacement[1];
replacementMap.put(from,to);
}
return replacementMap;
}
然后使用地图,以取代在其他文件中的话。