There are a number of ways you can go about this.
One is to declare an array of type String large enough to be certain that you will have enough space for the entire file. So if the file has 20 lines in it and you use one array element for each line you could declare the array length to be 100 or 1000. Then after reading the file and assigning each line (read from the file) to an array element you can copy the data from the big array into a new array that is the length that you need, ie, the length is the number of lines you read from the file.
Another is to read the file two times: once to count the lines and again filling an array declared and allocated to be the same length as the number of lines counted.
Another is really easy — use an ArrayList and add each line as you read. Then to convert it to an array use the List method
toArray(new String[list.size()].
Another is to add each line to the array as you read — demonstrated here:
import java.io.*;
public class InputTest {
public static void main(String[] args) {
String[] lines = new String[0];
String path = "input.txt";
BufferedReader br = null;
try {
File file = new File(path);
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
while( (line = br.readLine()) != null ) {
lines = add(line, lines);
}
br.close();
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
}
print(lines);
}
private static String[] add(String s, String[] array) {
int len = array.length;
String[] temp = new String[len+1];
System.arraycopy(array, 0, temp, 0, len);
temp[len] = s;
return temp;
}
private static void print(String[] data) {
for(int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
input.txt
Toyota
Subaru
Volkswagen
Chevrolet
Ford
Chrysler
Dodge
For info on array copying see the bottom of this page:
Arrays