我要存储以下格式的文本文件的内容:
第一行包含2个整数,例如n和k,以空格分隔。
以下几行包含n个整数(n可以非常大)(我想将其存储在ArrayList中)
通过在线搜索有关Java中文件处理方式的知识,我了解到BufferedReader是处理大输入时的首选方式,因为它更快(与Scanner相比)以及如何执行。我的尝试如下:
public static void main(String[] args) throws IOException {
StringBuilder t = new StringBuilder();
try(BufferedReader br = Files.newBufferedReader(Paths.get("./interview1.txt"))) {
t.append(br.readLine());
String[] firstLine = new String[2];
firstLine = t.toString().split(" ");
int n = Integer.parseInt(firstLine[0]);
// System.out.println(n);
int k = Integer.parseInt(firstLine[1]);
// System.out.println(k);
String line;
List<Integer> list = new ArrayList<>(n);
while((line = br.readLine()) != null){
String[] thisLine = line.split(" ");
for(int i = 0; i < thisLine.length; i++){
// System.out.print(thisLine[i] + " ");
list.add(Integer.valueOf(thisLine[i]));
}
}
} catch (Exception e) {
System.err.format("IOException: %s%n",e);
}
由于我知道第一行仅包含2个数字,因此我读取了该行,将其转换为大小为2的String数组,然后将2个Integer分开。到目前为止一切都很好。
在进入while循环之后,问题接着出现。在尝试将内容添加到列表中时,我不断收到java.lang.NumberFormatException(据我所知,这意味着我尝试将不包含可解析的int的String转换为Integer)。>
在for循环中取消注释第一行将产生以下输出:
3 4 2 1 6 7 1 2 2 3 (extra random 2 towards the end??)
当前使用的文件内容:
10 5
3 4 2 1 6 7 1 2 3
我在做什么错了?