簡體   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