Use a java.util.Scanner and java.util.List.

Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
  lines.add(sc.nextLine());
}

String[] arr = lines.toArray(new String[0]);
Answer from polygenelubricants on Stack Overflow
Discussions

Java: Reading a file into an array - Stack Overflow
I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers. The prob... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Java read file and store text in an array - Stack Overflow
I know how to read a file with Java using Scanner and File IOException, but the only thing I don't know is how to store the text in the files as an array. Here is a snippet of my code: public s... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to read from text file and store in String array in Java? - Stack Overflow
I have a text file textfile.txt which contains data as follows : A-abc , A-xyz , B-mno , A-ijk , B-pqr Now, i have to read from this file and store the values in two separate arrays "A" and "B" , ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 29, 2013
java - reading from text file to string array - Stack Overflow
So I can search for a string in my text file, however, I wanted to sort data within this ArrayList and implement an algorithm. Is it possible to read from a text file and the values [Strings] withi... More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 9, 2013
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ read a file into an arraylist
Read a File into an ArrayList | Baeldung
April 4, 2025 - In a nutshell, the method reads the content of the specified file line by line into a list of strings. As shown above, we can also add a charset to specify the character encoding to be used when reading the file. Please note that we donโ€™t need to use a try-with-resources here as the file is always automatically closed. Alternatively, we can use the Guava library to convert a file into an ArrayList.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ read-file-into-an-array-in-java
Read File Into an Array in Java - GeeksforGeeks
February 21, 2022 - Explanation: In this code, we used ... and stored/added in ArrayList and finally we converted that ArrayList to Array using toArray method....
๐ŸŒ
Brainly
brainly.com โ€บ computers and technology โ€บ high school โ€บ how do you create an array using a text file in java?
[FREE] How do you create an array using a text file in Java? - brainly.com
April 5, 2023 - To create an array from a text file in Java, first read the file using a Scanner, concatenate its contents into a single String, and then split that String into an array based on a delimiter. A sample code snippet demonstrates this process.
Find elsewhere
Top answer
1 of 7
16

Stored as strings:

public class ReadTemps {

    public static void main(String[] args) throws IOException {
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1
    String token1 = "";

    // for-each loop for calculating heat index of May - October

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");

    // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
    // List<String> temps = new LinkedList<String>();
    List<String> temps = new ArrayList<String>();

    // while loop
    while (inFile1.hasNext()) {
      // find next line
      token1 = inFile1.next();
      temps.add(token1);
    }
    inFile1.close();

    String[] tempsArray = temps.toArray(new String[0]);

    for (String s : tempsArray) {
      System.out.println(s);
    }
  }
}

For floats:

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class ReadTemps {

  public static void main(String[] args) throws IOException {
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1

    // for-each loop for calculating heat index of May - October

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");


    // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
    // List<Float> temps = new LinkedList<Float>();
    List<Float> temps = new ArrayList<Float>();

    // while loop
    while (inFile1.hasNext()) {
      // find next line
      float token1 = inFile1.nextFloat();
      temps.add(token1);
    }
    inFile1.close();

    Float[] tempsArray = temps.toArray(new Float[0]);

    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
}
2 of 7
2

If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :

List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
    tokens.add(inFile1.nextLine());
}

After that, if you need to, you can copy to an array :

String[] tokenArray = tokens.toArray(new String[0]);
๐ŸŒ
My Website
reimaginebelonging.de โ€บ home โ€บ java read text file example into array
Java Read Text File Example Into Array
May 5, 2026 - The most straightforward way to read a text file line by line is to use a BufferedReader. g.Worth adding: after reading each line, you add it to a dynamic collection (e. , ArrayList) and finally convert the list to a String[].
๐ŸŒ
w3resource
w3resource.com โ€บ java-exercises โ€บ io โ€บ java-io-exercise-14.php
Java - Store text file content line by line into an array
Write a Java program to store text file content line by line in an array. ... import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class Exercise14 { public static void main(String a[]){ StringBuilder sb = new StringBuilder(); String strLine = ""; List<String> list = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine != null) { strLine = br.readLine(); sb.append(str
๐ŸŒ
Java67
java67.com โ€บ 2016 โ€บ 07 โ€บ how-to-read-text-file-into-arraylist-in-java.html
How to read a text file into ArrayList in Java? Examples | Java67
This program first teaches you how to do this in JDK 7 or Java 8 using the Files.readAllLines() method and later using BufferedReader and ArrayList in Java 6 and lower version. You can compile and run this program from the command prompt or ...
Top answer
1 of 2
2
words[i] = inputFile.nextLine();

Here you are trying to store the next line from the input file into the index i of the words array. You have not declared or assigned a value to i, so Java won't know what you're trying to do.

With standard arrays, you must assign them an initial array value consisting of an explicit number of "slots" (indexes). With a Scanner, you could count the number of lines by reading them all and discarding the values. Once you have this counter, you can initialise the String[] with the appropriate size. Finally, you can read them all again and storing them into the array.

int counter = 0;

while (inputFile.hasNext()) {
    inputFile.nextLine();
    counter++;
}

inputFile = new Scanner(testFile); //to get to the beginning of the file

String[] words = new String[counter];

for (int i = 0; i < counter; i++) {
    words[i] = inputFile.nextLine();
}

This is very bad practice; reading the whole file merely to find its length is an overkill, and a waste of resources.

Therefore, it would be much better to use a collection type that automatically expands as you put elements into it, such as an ArrayList.

ArrayList<String> lines = new ArrayList<String>();

while (inputFile.hasNext()) {
    lines.add(inputFile.nextLine());
}

But it's likely that you're assignment requires you to use both Scanner and a standard String[]. In that case, you could change the size of the String[] manually:

String[] words = new String[0];

while (inputFile.hasNext()) {
    words = Arrays.copyOf(words, words.length + 1);
    words[words.length - 1] = inputFile.nextLine();
}

or

String[] words = new String[0];

while (inputFile.hasNext()) {
    String temp = new String[words.length + 1];
    System.arraycopy(words, 0, temp, 0, words.length);
    temp[temp.length - 1] = inputFile.nextLine();
    words = temp;
}
2 of 2
0

ArrayList words = new ArrayList(); while (inputFile.hasNextLine()){ String word = inputFile.getNextLine(); words.add(word); }

Since you don't know how big this is, you should use an arrayList. You can then sort alphabetically or whatever you need.

Top answer
1 of 3
2

There are a number of ways to do this. In order to effectively place the file contents into a Two Dimensional (2D) Array you will need to know how large your array will need to be in order to properly fit everything into it so as not to run into the problem of generating an ArrayOutOfBoundsException when you fill that array. The size of the Array needs to be established before you can place elements into it. Things to consider are:

  • Is it the right text file to begin with?
  • How many valid data lines are there in the file?
  • How many columns are there per line?
  • Are there any unwanted lines within the file (like a header line or blank lines)?

This is why using a collection mechanism like ArrayList, Map, HashMap, etc is a good way to tackle this. You can always convert that collection into an Array when your done retrieving the data.

By looking at your example file (well...the image of it :/) it looks like there is a Header Line which briefly describes what each data column in each file line is for. You didn't specify whether or not you want this to be part of your 2D Array. You also didn't specify the data type for your 2D Array, will it be Object, String, or will it be Integer?

With the above in mind we have to assume that you don't want the header line to be placed into the Array and you simply want the raw integer data values contained within each row column. This then answers the Array Data Type question....Integer (int).

Here is one way to carry out the task:

public int[][] readDataFile(String filePath) throws FileNotFoundException {
    ArrayList<int[]> list;
    // Try with resources...Auto closes scanner
    try (Scanner sRead = new Scanner(new File(filePath))) {
        list = new ArrayList<>();
        String line;
        int lineCounter = 0;
        while (sRead.hasNextLine()) {
            line = sRead.nextLine().trim();
            // Skip any blank lines
            if (line.equals("")) { continue; }
            lineCounter++;
            // Is it a valid data file?
            if (lineCounter == 1 && !line.startsWith("P1")) {
                // No it's not!
                JOptionPane.showMessageDialog(null, "Invalid Data File!",
                        "Invalid File!",
                        JOptionPane.WARNING_MESSAGE);
                return null;
            }
            // Skip the Header Line
            else if (line.startsWith("P1")) { continue; }

            // Split the incomming line and convert the
            // string values to int's
            String[] strArray = line.split("\\s+");
            int[] intArray = new int[strArray.length];
            for(int i = 0; i < strArray.length; i++) {
                intArray[i] = Integer.parseInt(strArray[i]);
            }
            // Add to ArrayList
            list.add(intArray);
        }
    }

    // Convert the ArrayList to a 2D int Array
    int[][] array = new int[list.size()][list.get(0).length];
    for (int i = 0; i < list.size(); i++) {
        System.arraycopy(list.get(i), 0, array[i], 0, list.get(i).length);
    }
    return array;
}

And to use this method you might go with:

try {
    int[][] a = readDataFile("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
    for (int[] a1 : a) {
        System.out.println(Arrays.toString(a1));
    }
} catch (FileNotFoundException ex) { ex.printStackTrace(); }
2 of 3
1

Use a list of String arrays and then convert this list into the 2D String array.
In this case, "result" will be your desired output.
Assumption: words in the input file are separated by tab

import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Final {
    public static void main (String [] args) throws Exception {
        File file = new File ("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        List<String[]> resultList = new ArrayList<>();
        while ((st=br.readLine()) !=null) {
            resultList.add(st.split("\t"));
        }
        String[][] result = new String[resultList.size()][resultList.get(0).length];
        for(int i=0; i<resultList.size(); i++) {
            result[i] = resultList.get(i);
        }
    }
}
๐ŸŒ
If Not Nil
ifnotnil.com โ€บ java
Load a text file (all at once) in an array? - Java - If Not Nil
August 19, 2024 - Hi, I have a text file, columns are tab delimited and lines are Return delimited. I want to load it and store its contents into an array. I have this code to load the file contents, but it use a While loop to do so (.RealAll will be nice instead). Hereโ€™s the code: import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; // Import the Scanner class to read text files public class ReadFile { publ...