Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Array populating it by .txt elements

I want to create an array, populating it while reading elements from a .txt file formatted like so:

item1
item2
item3

So the final result has to be an array like this:

String[] myArray = {item1, item2, item3}

Thanks in advance.

like image 934
Fseee Avatar asked Sep 15 '25 08:09

Fseee


1 Answers

  1. Wrap a BufferedReader around a FileReader so that you can easily read every line of the file;
  2. Store the lines in a List (assuming you don't know how many lines you are going to read);
  3. Convert the List to an array using toArray.

Simple implementation:

public static void main(String[] args) throws IOException {
    List<String> lines = new ArrayList<String>();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("file.txt"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
    } finally {
        reader.close();
    }
    String[] array = lines.toArray();
}
like image 194
João Silva Avatar answered Sep 16 '25 22:09

João Silva