You can use the LineNumberReader
.
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("names.txt"))); // Your file name
lnr.skip(Long.MAX_VALUE);
int size = lnr.getLineNumber() + 1; // +1 because line numbering begins at 0
lnr.close();
// Use the size for your array declarationg
String[] nameArray = new String[size];
Note: To know the size, the file has to be read twice(if the you insist on using an array), either by manually looping through it or letting built-in classes do that. Otherwise, the you can use an ArrayList
instead of an array, since an ArrayList
is dynamic and thus, you don't have to worry about fixing a size.