2017-08-15 17 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