0

I have a text file with some data, I want to read the file line by line then do find and replace.

In the text file i want to find "_x" and replace it with it's second previous line, that means i want the final output file like following

input

a
a=10
c=_x
b
b=20
d=_x


Output

a
a=10
c=a
b
b=20
d=b

I have tried to read the file line by line but i couldn't. How to read a text file line by line and replace the word with it's second previous line????

gar
  • 13,007
  • 5
  • 28
  • 30
Leks
  • 77
  • 11
  • [Here is an example of how to read the lines of a file and put them into a list.](http://stackoverflow.com/a/5343727/1682559) I would implement that first into your existing code, then try some things for replacing the `_x` with the previous line like you want. If you have any problems then, you can edit this post stating the **_specific_** problem you have, including the code you've made. Good luck. :) – Kevin Cruijssen Apr 13 '16 at 12:46

2 Answers2

0

To read your text-file line by line you need a construct like this:

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

When done your replacement-stuff, you want to write the "new" file like this:

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);
}
Martin
  • 229
  • 1
  • 15
0
Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("_", "");
Files.write(path, content.getBytes(charset));
Karthikeyan Vaithilingam
  • 6,473
  • 10
  • 41
  • 60
EL missaoui habib
  • 1,009
  • 1
  • 14
  • 24