从Java文本文件中删除特定行?

4

我想从文本文件中删除特定的一行。我找到了那一行,但接下来该怎么做呢?有什么想法吗?

6个回答

5

从流中读取文件并将其写入另一个流中,跳过您想要删除的行。


5

删除行并没有什么魔法。

  • 逐行复制文件,不复制你不想要的那一行。
  • 删除原始文件。
  • 将副本重命名为原始文件。

你可以通过向一个不存在的文件写入内容来创建一个新文件。你可以添加一个扩展名,比如.new来创建一个新文件。你也可以使用File.rename()来重命名它。 - Peter Lawrey

4

试一试这段代码。

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


class Solution {
    public static void main(String[] args) throws FileNotFoundException, IOException{

        File inputFile = new File("myFile.txt");
        File tempFile = new File("myTempFile.txt");

        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

        String lineToRemove = "bbb";
        String currentLine;

        while((currentLine = reader.readLine()) != null) {
            // trim newline when comparing with lineToRemove
            String trimmedLine = currentLine.trim();
            if(trimmedLine.equals(lineToRemove)) continue;
            writer.write(currentLine + System.getProperty("line.separator"));
        }
        writer.close(); 
        reader.close(); 
        boolean successful = tempFile.renameTo(inputFile);
        System.out.println(successful);

    }
}

2
尝试读取文件:
 public static String readAllText(String filename) throws Exception {
    StringBuilder sb = new StringBuilder();
    Files.lines(Paths.get(filename)).forEach(sb::append);
    return sb.toString();
}

然后根据特定字符(例如换行符“\n”)拆分文本。
private String changeFile(){
String file = readAllText("file1.txt"); 
String[] arr = file.split("\n"); // every arr items is a line now.
StringBuilder sb = new StringBuilder();
for(String s : arr)
{
   if(s.contains("characterfromlinewillbedeleted"))
   continue;
   sb.append(s); //If you want to split with new lines you can use sb.append(s + "\n");
}
return sb.toString(); //new file that does not contains that lines.
}

然后使用以下代码将此文件的字符串写入新文件:

public static void writeAllText(String text, String fileout) {
    try {
        PrintWriter pw = new PrintWriter(fileout);
        pw.print(text);
        pw.close();
    } catch (Exception e) {
        //handle exception here
    }
}


writeAllText(changeFile(),"newfilename.txt");

1
你应该将这里的“characterfromlinewillbedeleted”更改为你要删除的行。 - Tarık İNCE

1

直接在文件中删除文本行是不可能的。我们需要将文件读入内存,删除文本行并重新编写编辑后的内容。


1
尽管当然不必要将整个文件放入内存中,因为你可以在同一个循环中读取和写入。 - Simon Nickerson
@Simon - 我同意 - 我们不必将整个文件存储在内存中,但是,在最后,文件的每个字节都已被读取,在RAM中缓冲并写入新的目标文件。 - Andreas Dolk

0
也许一个搜索方法可以实现你想要的,即“搜索”方法接受一个字符串作为参数,并在文件中搜索并替换包含该字符串的行。
PS:
public static void search (String s)
{
    String buffer = "";
    try {

        Scanner scan = new Scanner (new File ("filename.txt"));
        while (scan.hasNext())
        {
            buffer = scan.nextLine();

            String [] splittedLine = buffer.split(" ");
            if (splittedLine[0].equals(s))
            {

                buffer = "";

            }
            else
            {
                //print some message that tells you that the string not found


            }
        }
        scan.close();

    } catch (FileNotFoundException e) {
        System.out.println("An error occured while searching in file!");
    }

}

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