Java 在文本文件中查找和替换
我有一个包含一些数据的文本文件,我想逐行读取文件,然后查找并替换 在文本文件中,我想找到“x”,并用它前面的第二行替换它,这意味着我想要最终的输出文件,如下所示Java 在文本文件中查找和替换,java,text,replace,find,Java,Text,Replace,Find,我有一个包含一些数据的文本文件,我想逐行读取文件,然后查找并替换 在文本文件中,我想找到“x”,并用它前面的第二行替换它,这意味着我想要最终的输出文件,如下所示 input a a=10 c=_x b b=20 d=_x Output a a=10 c=a b b=20 d=b 我试着一行一行地读文件,但我读不懂。如何逐行读取文本文件,并将单词替换为上一行的第二行???要逐行读取文本文件,您需要这样的构造: Charset charset = Charset.forName("US-A
input
a
a=10
c=_x
b
b=20
d=_x
Output
a
a=10
c=a
b
b=20
d=b
我试着一行一行地读文件,但我读不懂。如何逐行读取文本文件,并将单词替换为上一行的第二行???要逐行读取文本文件,您需要这样的构造:
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Charset charset = Charset.forName("US-ASCII");
String s = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
完成替换工作后,您希望像这样编写“新”文件:
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Charset charset = Charset.forName("US-ASCII");
String s = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
我将首先在您现有的代码中实现这一点,然后尝试一些方法,用您想要的前一行替换\ux
。如果你有任何问题,你可以编辑这篇文章,说明你的具体问题,包括你的代码。祝你好运