从文件中删除冗余行



就是这样,使用这个函数:

  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());
            }
        }
      }
    }
  }

我在第二个函数中的想法如下:将第一行写入新文件,然后将第二行与之比较,如果不同则写入,然后将第三行与两者比较…但我的函数似乎很烂。任何帮助吗?

创建一行的Set。考虑以下伪代码:

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

将文件一行一行地读入Set,最后从Set的数据中写入新文件

好吧,你的方法可以更好。我想这可能是家庭作业,所以我不打算发布任何代码…

对于Normalize函数,

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

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

最新更新