从文件中删除冗余行

时间:2011-12-16 12:07:07

标签: java file

这是使用此功能:

  private static void write(String Swrite) throws IOException {
    if (!StopWordRemoval.exists()) {
      StopWordRemoval.createNewFile();
    }
    FileOutputStream fop = new FileOutputStream(file);
    if (Swrite != null)
      fop.write(Swrite.getBytes());
    fop.flush();
    fop.close();
  }

我的程序从用户获取字符串并将其写入文件。在所有用户完成输入信息后,我想删除多余的信息。如果两个确切的行,那么一个删除。首先我尝试了以下代码,但没有说明:

  private static void Normalize(File file) throws FileNotFoundException, IOException {
    String tempLine2;
    BufferedReader buf = new BufferedReader(new FileReader(file));
    FileOutputStream fop = new FileOutputStream(temp, true);
    String tempLine = null;
    tempLine = buf.readLine();
    fop.write(tempLine.getBytes());
    BufferedReader buf2 = new BufferedReader(new FileReader(temp));

    while ((tempLine = buf.readLine()) != null) {
      while ((tempLine2 = buf2.readLine()) != null) {
        if (!tempLine.trim().equals(tempLine2)) {
          if (tempLine != null)
            for (final String s : tempLine.split(" ")) {
              fop.write(s.getBytes());
              fop.write(System.getProperty("line.separator").getBytes());
            }
        }
      }
    }
  }

我在第二个函数中的想法如下:将第一行写入一个新文件,然后将第二行与它进行比较,如果不同则写入,然后将第三行与两者进行比较......但似乎我的功能很糟糕。有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

创建Set行。考虑这个伪代码:

Set<String> uniqueLines = new HashSet<String>();
String line = readLine();
if (!uniqueLines.contains(line)) {
   write_to_file(line);
   uniqueLines.add(line);
}

答案 1 :(得分:2)

只需将文件逐行读入Set,最后根据Set

中的数据写入新文件

答案 2 :(得分:2)

好的,你的方法可以更好。我认为这可能是家庭作业,所以我不会发布任何代码......

对于Normalize函数,

  1. 打开文件
  2. 声明并初始化Set<String>(TreeSet将为您提供排序结果)
  3. 读取每行并将其添加到Set
  4. 使用Set作为每一行的条目覆盖该文件。

    (解释:关闭FileInputStream,并创建一个new PrintStream(sameFile);,这将基本上删除以前的内容,然后启动out.println(eachLine),最后关闭文件)

  5. 完成。