简体   繁体   English

读取特定行并更改该行Java中的字符串

[英]Read Specific Line and change String in that Line Java

I have a text file called "Hello.txt" It has the following contents: 我有一个名为“Hello.txt”的文本文件它具有以下内容:

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. 我希望有一种方法来检查当读者读取行时,如果行等于2,它将“cat”替换为“hen”并写回同一文件。 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: 到目前为止我已经尝试了这么多,我不知道在哪里放条件检查线是否= 2,然后它做了替换。我的代码是:

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. 我想要一个条件(行号= 2),然后它取代它。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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