在文件中找到一行并删除它我正在寻找一个小的代码片段,它将在文件中找到一行并删除该行(不是内容,而是行),但找不到。因此,例如,我在一个文件中有以下内容:myFile.txt:aaa
bbb
ccc
ddd需要有这样的功能:public void removeLine(String lineContent),如果我通过removeLine("bbb")我得到了这样的文件:myFile.txt:aaa
ccc
ddd
3 回答
绝地无双
TA贡献1946条经验 获得超4个赞
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);
慕容森
TA贡献1853条经验 获得超18个赞
public void removeLineFromFile(String file, String lineToRemove) { try { File inFile = new File(file); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; //Read from the original file and write to the new //unless content matches data to be removed. while ((line = br.readLine()) != null) { if (!line.trim().equals(lineToRemove)) { pw.println(line); pw.flush(); } } pw.close(); br.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
添加回答
举报
0/150
提交
取消