2017-08-15 35 views
0

我需要刪除從txt文件一個如何從txt文件與緩衝讀者的Java

FileReader fr= new FileReader("Name3.txt"); 

BufferedReader br = new BufferedReader(fr); 

String str = br.readLine(); 

br.close(); 

線刪除線,我不知道該繼續的代碼。

+0

當你說「刪除」,你的意思是你想修改底層文件嗎?讀者不這樣做。 –

+0

你想刪除哪條線?最後一行?第一行?一個特定的線?所有的線? – Jeyaprakash

+0

Wel *你不能*用'BufferedReader'來完成。奇怪的標題。 – EJP

回答

0

您可以讀取所有行並將它們存儲在列表中。在存儲所有行的同時,假設您知道要刪除的行,只需檢查您不想存儲的行,然後跳過它們即可。然後將列表內容寫入文件。

//This is the file you are reading from/writing to 
    File file = new File("file.txt"); 
    //Creates a reader for the file 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    String line = ""; 

    //This is your buffer, where you are writing all your lines to 
    List<String> fileContents = new ArrayList<String>(); 

    //loop through each line 
    while ((line = br.readLine()) != null) { 
     //if the line we're on contains the text we don't want to add, skip it 
     if (line.contains("TEXT_TO_IGNORE")) { 
      //skip 
      continue; 
     } 
     //if we get here, we assume that we want the text, so add it 
     fileContents.add(line); 
    } 

    //close our reader so we can re-use the file 
    br.close(); 

    //create a writer 
    BufferedWriter bw = new BufferedWriter(new FileWriter(file)); 

    //loop through our buffer 
    for (String s : fileContents) { 
     //write the line to our file 
     bw.write(s); 
     bw.newLine(); 
    } 

    //close the writer 
    bw.close(); 
+0

我不明白你的代碼可以解釋我 – ezscript

+0

當然,我已經添加了對代碼的評論 – user

+0

在Java 8中,整個閱讀段基本上可以用'List fileContents = Files.lines(file.toPath() ).filter(line - >!line.contains(「TEXT_TO_IGNORE」))。collect(Collectors.toCollection(ArrayList :: new));'' – tradeJmark