I'm trying to add an item of an arraylist into a txt file but i need to do it line by line. The txt file contains names and i'm trying to add their username so i need to do add each user line by line. This is the original txt file:
Smith, Will
Lothbrok, Ragnar
Skywalker, Anakin
Ronaldo, Cristiano
Messi, Lionel
This is the method i'm using:
public static void addUsers(int maxLines, List<Users> users) throws IOException {
File f = new File("Users.txt");
FileOutputStream fos = new FileOutputStream(f, true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
//maxLines is just a count of the lines from the text file so i can put the limit of this loop.
for (int i = 0; i < maxLines; i++) {
bw.write(" > " + users.get(i).getUsername() );
bw.newLine();
}
bw.close();
}
The result i get after this is:
Smith, Will
Lothbrok, Ragnar
Skywalker, Anakin
Ronaldo, Cristiano
Messi, Lionel
> Will.Smith3
> Ragnar.Lothbrok74
> Anakin.Skywalker30
> Cristiano.Ronaldo32
> Lionel.Messi2
But i need it to be like:
Smith, Will > Will.Smith3
Lothbrok, Ragnar > Ragnar.Lothbrok74
Skywalker, Anakin > Anakin.Skywalker30
Ronaldo, Cristiano > Cristiano.Ronaldo32
Messi, Lionel > Lionel.Messi2
I've being trying different things like putting append not write in the BufferedWriter method but it still giving the same result. How could i do it better?