In order to remove lines from a text file, I do the following:
public void removeTagLine(String tag, String filename)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
//String buffer to store contents of the file
StringBuffer sb=new StringBuffer("");
String line;
while((line=br.readLine())!=null)
{
//Store each valid line in the string buffer
if(!line.contains(tag))
sb.append(line+"\n"); //here
}
br.close();
FileWriter fw=new FileWriter(new File(filename));
//Write entire string buffer into the file
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
This works exactly as I'd hope, except I lose all my newLines. It's worth noting that my newlines were done by doing
writer.newLine();
As you can see where I marked the comment //here , am adding a \n, yet the new file with the removed lines is still all in one line. What gives?
Use
System.getProperty("line.separator");
instead of\n
to avoid any platform dependency.Line separators might vary depending on the OS used:
\n
- *nix systems\r\n
- Windows systems