如何编辑我的比较方法

2022-01-25 00:00:00 string arrays compare java filewriter

我想比较我的两个 txt 文件的内容并将不同的单词写入其他 file3.txt 文件中

I want to compare contens of my two txt files and write the different words in other file3.txt file

我想用这种方式做比较方法来写另一个txt文件.我也不编码有错误

I want to do compare method in this way to write another txt file. Also I dont have an error for coding

我没有结果.这是我的代码

I don't have a result. here is my code

推荐答案

我已将您的代码简化并更正为:

I have simplified and corrected your code into this:

public class TextAreaSample
{
  public static void main(String [] args) throws IOException {
    compare(readFileAsList("deneme1.txt"),
            readFileAsList("deneme2.txt"));
  }

  private static void compare(List<String> strings1, List<String> strings2)
  throws IOException
  {
    final Collator c = Collator.getInstance();
    c.setStrength(Collator.PRIMARY);
    final SortedSet<String>
      union = new TreeSet<String>(c),
      intersection = new TreeSet<String>(c);
    union.addAll(strings1);
    union.addAll(strings2);
    intersection.addAll(strings1);
    intersection.retainAll(strings2);
    union.removeAll(intersection);
    write(union, "deneme3.txt");
  }

  private static void write(Collection<String> out, String fname) throws IOException {
    FileWriter writer = new FileWriter(new File(fname));
    try { for (String s : out) writer.write(s + "
"); }
    finally { writer.close(); }
  }

  private static List<String> readFileAsList(String name) throws IOException {
    final List<String> ret = new ArrayList<String>();
    final BufferedReader br = new BufferedReader(new FileReader(name));
    try {
      String strLine;
      while ((strLine = br.readLine()) != null) ret.add(strLine);
      return ret;
    } finally { br.close(); }
  }
}

我有 deneme1.txt:

I have deneme1.txt:

plane
horoscope
microscope

deneme2.txt:

deneme2.txt:

phone
mobile
plane

在 deneme3.txt 中输出:

Output in deneme3.txt:

horoscope
microscope
mobile
phone

相关文章