3

I want to open a file and then read it line by line. In some lines I want to append a string to exactly this line. Is this possible?

I have a code for opening the file and reading it like the following:

File file = new File("MyFile.txt");
BufferedReader bufRdr = new BufferedReader(new FileReader(file));

String line = null;

try {
    while((line = bufRdr.readLine()) != null)
    {
        // read line by line and append some string to the line

    }
} catch (IOException e) {
    // ...
}

but how can I append a string to the current line and write this to the file?

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
gurehbgui
  • 14,236
  • 32
  • 106
  • 178

3 Answers3

2

As you are reading file line by line. append your text to line and write it to other file. Say for example file with different name and later you can rename the file.

Just like

try {
   while((line = bufRdr.readLine()) != null)
    {
    // read line by line and append some string to the line
    //pseudo code
    newline = line + "yourtext";
    outputstreamtootherfile.write(newline);

    }
} 

I think there is no way you can read and write to same file concurrently, as it holds read/write locks.

Thanks

Chakradhar K
  • 501
  • 13
  • 40
0

Create new file and keep on writing to this file (as you read other file line by line) with the modification you want. Then delete the existing one and give the newly created file the name of deleted file.This is how i would approach it.

Here is the link which confirms this approach alongwith other alternatives.

Modify a .txt file in Java

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314
0
  1. readLines read lines to List<String> and change some String (line) if you need it
  2. create new temp file
  3. write lines (or line by line) to it by append
  4. remove old file
  5. rename
dantuch
  • 9,123
  • 6
  • 45
  • 68