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.
BufferedReader around a FileReader so that you can easily read every line of the file;List (assuming you don't know how many lines you are going to read);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();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With