MadMax
MadMax

Reputation: 101

How to append an arraylist line by line into a txt file?

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?

Upvotes: 1

Views: 153

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79155

  1. You should use try-with-resources to get the resource closed automatically.
  2. store lines from the file plus corresponding username into a List<String> while reading the file. Once the reading is completed, write the content of this list into the file.

Demo:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class User {
    private String username;

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

public class Main {
    public static void main(String[] args) {
        // Test
        List<User> users = List.of(new User("Will.Smith3"), new User("Ragnar.Lothbrok74"),
                new User("Anakin.Skywalker30"), new User("Cristiano.Ronaldo32"), new User("Lionel.Messi2"));
        try {
            addUsers(5, users);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void addUsers(int maxLines, List<User> users) throws IOException {
        // List to store lines from the file plus corresponding username
        List<String> list = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(new File("Users.txt")))) {
            String currentLine;
            int line = 0;
            while ((currentLine = reader.readLine()) != null && line < users.size()) {
                list.add(line, currentLine + " > " + users.get(line).getUsername() + System.lineSeparator());
                line++;
            }
        }

        // Write the content of the list into the file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("Users.txt")))) {
            for (String s : list) {
                writer.write(s);
            }
        }
    }
}

Upvotes: 3

Related Questions