TMachna
TMachna

Reputation: 289

Java. How to add text to each line

I need to add in loop text at the end of each line in the file.

For example, my file look like:

Adam
Maria
Jon

Now in loop, I need to add next columns, to look like:

Adam|Kowalski
Maria|Smith
Jon|Jons

3rd column:

Adam|Kowalski|1999
Maria|Smith|2013
Jon|Jons|1983

And so on. How to do that effectively ? One limit of my program is, that i dont know all of the new value to add, I mean i can't write "|Kowalski|1999" at once, need to write "|Kowalski" then in add "|1999"

Thanks

Upvotes: 0

Views: 722

Answers (1)

Bahramdun Adil
Bahramdun Adil

Reputation: 6079

You can try something like this:

public static void main(String[] args) throws Exception {// for test I throw the Exception to keep code shorter.
    StringBuilder sb = new StringBuilder();
    String path = "the/path/to/file";
    BufferedReader bReader = new BufferedReader(new FileReader(path));
    String line;
    while ((line = bReader.readLine()) != null) {
        line += "|"+"the-text-to-add"+"\n\r";
        sb.append(line);
    }
    bReader.close();

    // now write it back to the file
    OutputStream out = new FileOutputStream(new File(path));
    out.write(sb.toString().getBytes());
    out.close();
}

Upvotes: 1

Related Questions