繁体   English   中英

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

[英]Delete Specific Line From Java Text File?

我想从文本文件中删除特定行。 我找到了那条线,但下一步该怎么做? 任何想法?

去除线条没有魔法。

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

从 stream 读取文件并将其写入另一个 stream 并跳过要删除的行

尝试读取文件:

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

试试这个代码。

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

    }
}

无法直接删除文件中的文本行 我们必须将文件读入memory,删除文本行并重写编辑内容。

也许搜索方法会做你想要的,即“搜索”方法将字符串作为参数并将其搜索到文件中并替换包含该字符串的行。

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