简体   繁体   中英

Read Specific Line and change String in that Line Java

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.

Something like this?

int lineCount = 1;
while((line = reader.readLine()) != null)
{
  if (lineCount == 2)
    oldText += parseCommand.replaceFirst("\\w*( ?)", "hen\1")
      + System.lineSeparator();
    //oldText += "hen" + System.lineSeparator();
  else
    oldtext += line + System.lineSeparator();
  lineCount++;
}

Reference .

You could create a variable to keep track of which line number you are at, like so:

int line = 0;
while((line = reader.readLine()) != null)

    if (line == 1)
    {
       oldtext += line + System.lineSeparator();
     }
    ++line;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM