如何删除文本文件中的行?

3

如何使用Java删除文本文件的前两行?


请使用正确的大写格式编写您的问题。 - jzd
6个回答

2

读取文件并将除前两行以外的所有内容写回。


1
这需要创建整个文件的内存副本。更经济的实现方法是使用一个标志来指示是否已读取前两行,并在跳过前两行后逐个复制字符。 - Raedwald
@Raedwald。我同意。然而,问题似乎并没有表明文件大小是一个因素,所以我认为除非这成为一个问题,否则我会保持简单,不提及它。 - jzd

2
  1. 打开要阅读的文件,并创建一个新的临时文件来进行写入操作
  2. 逐行阅读,同时计数器递增,将每一行读取后写入到临时文件中
  3. 当读取到需要删除的行号时,跳过临时文件的写入操作
  4. 继续阅读直到文件末尾
  5. 将临时文件重命名为原文件名

如果您希望通过索引引用要排除的行,就像您提供的示例一样,则此方法非常适用。它不会将整个文件加载到内存中。


1

这里是一个 Guava 的解决方案:

public static void removeLines(final File targetFile,
    final Charset charSet,
    final Collection<Integer> lineNumbers) throws IOException{
    final List<String> lines = Files.readLines(targetFile, charSet);
    // line numbers need to be sorted in reverse.
    // if they are, you can replace everything from Ordering until )){
    // with 'lineNumbers){'
    for(final Integer lineNumber : Ordering
        .natural()
        .reverse()
        .immutableSortedCopy(lineNumbers)){
        lines.remove(lineNumber.intValue());
    }
    Files.write(Joiner.on('\n').join(lines), targetFile, charSet);
}

是的,整个文件都被读入内存中,所以不要尝试使用大型服务器日志文件。


1

3
但是这并没有回答问题。 - Jesper

0

这是我从目标文件中删除前20行的方法...

class removeLines{
public static void main(String[] args){
    try{
        //Here I am opening the target File named 1.txt......
        File targetFile = new File("1.txt");
        BufferedReader targetBuf = new BufferedReader(new FileReader(targetFile));

        //Opening a Temp file.......
        File tempFile = new File("temp.txt");
        PrintWriter printTemp = new PrintWriter(tempFile);

            //Here is the important part... skipping first 20 lines.... 
            for(int i=1;i<=20;i++){
            targetBuf.readLine();
        }
        String notfau;
        while((notfau = targetBuf.readLine())!=null){
            printTemp.println(notfau);
        }
        //closing the files after finished copying from target file to temp file....
        targetBuf.close();
        printTemp.close();
        //Now replace and delete the target file with temp file....
        targetFile.delete();
        tempFile.renameTo(targetFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}


-1

以下是方法:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {


  public void removeLineFromFile(String file, String lineToRemove) {

    try {

      File inFile = new File(file);

      if (!inFile.isFile()) {
        System.out.println("Parameter is not an existing file");
        return;
      }

      // Construct the new file that will later be renamed
      // to the original filename. 
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

      BufferedReader br = new BufferedReader(new FileReader(file));
      PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

      String line = null;

      //Read from the original file and write to the new 
      //unless content matches data to be removed.
      while ((line = br.readLine()) != null) {

        if (!line.trim().equals(lineToRemove)) {

          pw.println(line);
          pw.flush();
        }
      }
      pw.close();
      br.close();

      //Delete the original file
      if (!inFile.delete()) {
        System.out.println("Could not delete file");
        return;
      } 

      //Rename the new file to the filename the original file had.
      if (!tempFile.renameTo(inFile))
        System.out.println("Could not rename file");

    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static void main(String[] args) {
    FileUtil util = new FileUtil();
    util.removeLineFromFile("test.txt", "bbbbb");
  }
}

3
从英语翻译成中文:复制自http://www.javadb.com/remove-a-line-from-a-text-file?但这不是问题的好解决方案。 - rogeriopvl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接