I need to replace first line of a file. So I am doing it in a usual way by reading the file line by line and replacing the first line and then appending all other line and then finally writing it back. Using count
variable to count line number as an optimization as it will prevent other equals()
comparison to run.
In case someone wants to replace nth line, count
can be tweaked easily for the same.
My question is - do we really need to read whole file even it is known that replacement has to be done in just first line? Is there a way to avoid reading of other lines and still be able to modify this file?
private void replaceFirstLine(File file)
{
BufferedReader bufferedReader = null;
FileWriter writer = null;
try
{
bufferedReader = new BufferedReader(new FileReader(file));
String line = bufferedReader.readLine();
String content = "";
int count = 0;
while (line != null)
{
if(count < 1 && line.equals(CURRENT_FIRST_LINE))
{
line = EXPECTED_FIRST_LINE;
count++;
}
content = content + line + System.lineSeparator();
line = bufferedReader.readLine();
}
writer = new FileWriter(file);
writer.write(content);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
//Closing the resources
bufferedReader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}