读取特定行并更改该行Java中的字符串 [英] Read Specific Line and change String in that Line Java
问题描述
我有一个名为"Hello.txt"的文本文件 它具有以下内容:
dog
cat
mouse
horse
我想有一种方法来检查读者在读取行时,如果行等于2,它将"cat"替换为"hen"并写回同一文件.到目前为止,我已经尝试了很多次,但我不知道将条件放在哪里检查line = 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();
}
}
}
文件内容应如下所示:
dog
hen
mouse
horse
我上面发布的代码行之有效,因为它只是用母鸡代替了cat.我想要一个条件(行号= 2),然后将其替换.
像这样吗?
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++;
}
参考. >
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++;
}
这篇关于读取特定行并更改该行Java中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!