I have a text file called "Hello.txt" It has the following contents:
dog
cat
mouse
horse
I want to have a way to check that when reader is reading the lines, if the line equals 2, it replaces "cat" with "hen" and write back to the same file. I have tried this much so far and i dont know where to put the condition to check if line=2, then it does the replacing.My codes are:
import java.io.*;
public class Python_Read_Replace_Line
{
public static void main(String args[])
{
try
{
File file = new File("C:\\Hello.py");
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:\\Hello.txt")));
int numlines = lnr.getLineNumber();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + System.lineSeparator();
}
reader.close();
String newtext = oldtext.replaceFirst("cat", "hen");
FileWriter writer = new FileWriter("C:\\Hello.txt");
writer.write(newtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
The file contents should be something like this:
dog
hen
mouse
horse
The code I posted above works because it just replaces cat with hen. I want to have a condition (line number=2), then it replaces it.
You could create a variable to keep track of which line number you are at, like so:
Something like this?
Reference.