如何删除文本文件的行?

时间:2010-12-29 16:08:47

标签: java file

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

6 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

  1. 打开要读取的文件,并创建一个新的临时文件以写入
  2. 逐行读取,递增行计数器,每行读取该行写入临时文件
  3. 点击要删除的行的索引后,跳过临时文件写入
  4. 继续阅读直到文件结尾
  5. 将临时文件重命名为原始文件名
  6. 如果你想通过索引引用要排除的行,就像你给出的例子一样。并且它不会将整个文件加载到内存中。

答案 2 :(得分:1)

在此处阅读文件的非常好的示例:http://www.kodejava.org/examples/266.html

答案 3 :(得分: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);
}

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

答案 4 :(得分:0)

以下是我从targetFile中删除前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();
    }

}

}

答案 5 :(得分:-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");
  }
}
相关问题