简体   繁体   English

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

[英]Delete Specific Line From Java Text File?

I want to delete a specific line from a text file.我想从文本文件中删除特定行。 I found that line, but what to do next?我找到了那条线,但下一步该怎么做? Any idea?任何想法?

There is no magic to removing lines.去除线条没有魔法。

  • Copy the file line by line, without the line you don't want.逐行复制文件,没有你不想要的行。
  • Delete the original file.删除原始文件。
  • rename the copy as the original file.将副本重命名为原始文件。

Read file from stream and write it to another stream and skip the line which you want to delete从 stream 读取文件并将其写入另一个 stream 并跳过要删除的行

Try to read file:尝试读取文件:

 public static String readAllText(String filename) throws Exception {
    StringBuilder sb = new StringBuilder();
    Files.lines(Paths.get(filename)).forEach(sb::append);
    return sb.toString();
}

then split text from specific character (for new line "\n")然后从特定字符中拆分文本(对于新行“\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.
}

then write this file's string to new file with:然后将此文件的字符串写入新文件:

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

Try this code.试试这个代码。

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

    }
}

Deleting a text line directly in a file is not possible.无法直接删除文件中的文本行 We have to read the file into memory, remove the text line and rewrite the edited content.我们必须将文件读入memory,删除文本行并重写编辑内容。

Maybe a search method would do what you want ie "search" method takes a string as a parameter and search for it into the file and replace the line contains that string.也许搜索方法会做你想要的,即“搜索”方法将字符串作为参数并将其搜索到文件中并替换包含该字符串的行。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM