Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何删除文本文件的行?_Java_File - Fatal编程技术网

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

Java 如何删除文本文件的行?,java,file,Java,File,如何使用Java删除文本文件的前两行?读取文件并写回除前两行以外的所有内容。以下是如何: 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; publ

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

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

以下是如何:

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

这里是读取文件的非常好的示例:

  • 打开要读取的文件,并创建要写入的新临时文件
  • 逐行读取,递增一行计数器,对于每行读取,将该行写入临时文件
  • 一旦找到要删除的行的索引,请跳过临时文件写入
  • 继续阅读直到文件结束
  • 重命名临时文件,使其具有原始文件名
  • 如果您希望通过索引引用要排除的行,如您给出的示例中所示,则此方法有效。而且它不会将整个文件加载到内存中。

    这里有一个解决方案:

    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);
    }
    
    publicstaticvoidremovelines(最终文件targetFile,
    最终字符集字符集,
    最终收集行号)引发IOException{
    最终列表行=Files.readLines(targetFile,字符集);
    //行号需要反向排序。
    //如果是,您可以从订购到更换所有产品{
    //使用“行号”{
    对于(最终整数行号:排序)
    .natural()
    .reverse()
    .immutableSortedCopy(行号)){
    lines.remove(lineNumber.intValue());
    }
    write(Joiner.on('\n').join(行),targetFile,charSet);
    }
    

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

    以下是我如何从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();
        }
    
    }
    
    类移除{
    公共静态void main(字符串[]args){
    试一试{
    //在这里,我正在打开名为1.txt的目标文件。。。。。。
    File targetFile=新文件(“1.txt”);
    BufferedReader targetBuf=新的BufferedReader(新文件读取器(targetFile));
    //正在打开临时文件。。。。。。。
    File tempFile=新文件(“temp.txt”);
    PrintWriter printTemp=新的PrintWriter(tempFile);
    //这里是重要的部分…跳过前20行。。。。
    
    对于(int i=1;i请将您的问题格式化为正确的大小写。但这并不能回答问题。复制自?这也不是解决问题的好办法。这需要创建整个文件的内存副本。更经济的实现是使用标志指示前两行是否已读取,并复制字符在前两行被跳过后的某个时间执行。@Raedwald。我同意。但是,这个问题似乎并没有表明文件大小是一个因素,所以我想我会保持简单,不提这个问题,除非这是一个问题。