Create an array filling it with .txt elements

I want to create an array by filling it when reading elements from a TXT file formatted like this:

item1
item2
item3

So, the final result should be such an array:

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

Thanks in advance.

+3
source share
2 answers
  • Wrap BufferedReaderaround FileReaderso you can easily read every line of the file;
  • Store the lines in List(assuming you don't know how many lines you are going to read);
  • Convert Listto an array with 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();
}
+2
source

It smells of homework. If you need to re-read your notes and tell us what you tried.

Personally, I would use a scanner (from java.util).

import java.io.*;
import java.util.*;

public class Franky {
    public static void main(String[] args) {
        Scanner sc = new Scanner(new File("myfile.txt"));
        String[] items = new String[3]; // use ArrayList if you don't know how many
        int i = 0;
        while(sc.hasNextLine() && i < items.length) {
            items[i] = sc.nextLine();
            i++;
        }
    }

}
+1
source

All Articles