我想比较我的两个txt文件的内容,并将不同的单词写入另一个file3.txt文件中
我想用这种方式进行比较方法来写入另一个txt文件。我也没有 编码错误
我没有结果。这是我的代码
最佳答案
我刚刚使用以下文件运行了您的程序,但无法重现您的问题。
deneme1
abc
def
ghi
deneme2
abc
ghi
klm
并且deneme3是使用以下内容创建的:
abc
ghi
编辑
看来您想要相反的行为。您的某些方法不必要地复杂,通过使用标准 JDK 的正确工具可以使其变得更短。请参阅下面的简化实现示例(仅保留两个文件之间不常见的单词) - 此示例区分大小写:
public class TextAreaSample {
public static void main(String[] args) throws IOException {
//readAllLines does what you do in readFileAsList
List<String> strings1 = Files.readAllLines(Paths.get("C:/temp/deneme1.txt"), Charset.defaultCharset());
List<String> strings2 = Files.readAllLines(Paths.get("C:\\temp\\deneme2.txt"), Charset.defaultCharset());
Set<String> notInCommon = getNotInCommon(strings1, strings2);
write(notInCommon, "C:\\temp\\deneme3.txt");
}
private static void write(Collection<String> out, String fname) throws IOException {
FileWriter writer = new FileWriter(new File("C:\\temp\\deneme3.txt"));
for (String s : out) {
writer.write(s + "\n");
}
writer.close();
}
private static Set<String> getNotInCommon(List<String> strings1, List<String> strings2) {
//Sets are great to get unique lists and check commonality
Set<String> onlyInFile1 = new HashSet<String>(strings1);
onlyInFile1.removeAll(strings2); //remove strings in s1 AND s2
Set<String> onlyInFile2 = new HashSet<String>(strings2);
onlyInFile2.removeAll(strings1); //remove strings in s1 AND s2
Set<String> notInCommon = new HashSet<>();
notInCommon.addAll(onlyInFile1);
notInCommon.addAll(onlyInFile2);
return notInCommon;
}
}
关于java - 如何编辑我的比较方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11792534/