How do I delete rows of a text file?

2020-04-11 11:03发布

How can I delete the first two rows of a text file with Java?

标签: java file
6条回答
劫难
2楼-- · 2020-04-11 11:32
  1. Open the file to read, and create a new temp file to write to
  2. Read line by line, incrementing a line counter, for each line read write that line to the temp file
  3. Once you hit the index of the lines you want to remove, skip the temp file writing
  4. Keep on reading until the end of the file
  5. Rename the temp file to have the original file name

This works if you wish to reference the lines to exclude, by index, like in the example you gave. And it does not load the entire file into memory.

查看更多
干净又极端
3楼-- · 2020-04-11 11:38

Read the file and write back everything but the first two rows.

查看更多
乱世女痞
4楼-- · 2020-04-11 11:40

Very good example of reading a file here: http://www.kodejava.org/examples/266.html

查看更多
ら.Afraid
5楼-- · 2020-04-11 11:41

Here is a Guava solution:

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

Yes, the entire file is read into memory, so don't try this with huge server log files.

查看更多
一纸荒年 Trace。
6楼-- · 2020-04-11 11:42

Here is how I am deleting first 20 lines from the targetFile...

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

}

}

查看更多
甜甜的少女心
7楼-- · 2020-04-11 11:42

Here's how:

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");
  }
}
查看更多
登录 后发表回答