Java数组的大小不能增长,因此您使用了一个列表(来自java.util)。这些列表动态增长,因此您可以随意使用add()
。由于列表可能包含所有内容,因此可以使用List<TypeOfWhatYouWantToStore>
指定要包含的内容。因此,List类被称为泛型类。
将它转换为数组(因为这是你想要的)有点奇怪。您分配列表大小的阵列,然后在列表上使用toArray
。这将返回列表,并转换为数组。它必须将数组作为参数,因为编译器需要使用泛型进行编译。
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);
}
}
编辑:使用Files.readAllLines()
(见你的问题的意见)是更容易和更快的可能,但使用这个循环中,你可以看到更多的是怎么回事的。
编辑2:更常见的是使用这种循环:
String temp;
List<String> tmpList = new ArrayList<>();
while ((temp = br.readLine()) != null) {
tmpList.add(temp);
}
环路现在做了以下内容:
- 读
br.readLine()
到temp
- 如果
temp
为空,离开循环
- 如果
temp
不为空,则添加i吨至列表
您还可以通过执行打印数组:
for (String str : myArray) {
System.out.println(str);
}
至于你的问题,我也搞不清楚初学者...你有什么问题吗?你有什么问题? – Tom
使用['Files.readAllLines()'](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path- java.nio.charset.Charset-)。 – fge