Java Arrays can't grow in size, so you use a list (from java.util). The lists grow dynamically, so you can use add()
as often as you want. As a list can potentially hold everything, you specify what you want it to contain by using List<TypeOfWhatYouWantToStore>
. The List class is called a generic class because of that.
Converting it to an array (because that is what you wanted) is a bit strange. You allocate the array with the size of the list and then you use toArray
on the list. This returns the list, converted as an array. It must take the array as a parameter, because the compiler needs that when compiling with generics.
package com.java24hours;
import java.io.*;
import java.util.*;
public class ShorteningVelocity {
public static void main(String[] arguments) throws IOException {
FileReader SVfile = new FileReader(new File("C:\\Documents\\10-27-15110mMKPSS3.dat"));
BufferedReader br = new BufferedReader(SVfile);
String temp = br.readLine();
List<String> tmpList = new ArrayList<>();
while (temp != null) {
tmpList.add(temp);
temp = br.readLine(); //reads file line by line
}
String[] myArray = new String[tmpList.size()];
myArray = tmpList.toArray(myArray);
}
}
EDIT: Using Files.readAllLines()
(see comments on your question) is easier and potentially faster, but using this loop, you can see more of what's going on.
EDIT 2: It is more common use this loop:
String temp;
List<String> tmpList = new ArrayList<>();
while ((temp = br.readLine()) != null) {
tmpList.add(temp);
}
The loop is now doing the following:
- Read
br.readLine()
into temp
- If
temp
is null, leave the loop
- If
temp
is not null, add it to the list
You can also print the array by doing:
for (String str : myArray) {
System.out.println(str);
}