Java的:读从文件整数到一个数组 [英] Java: Reading integers from a file into an array
本文介绍了Java的:读从文件整数到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
File fil = new File("Tall.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
int [] tall = new int [100];
String s =in.readLine();
while(s!=null)
{
int i = 0;
tall[i] = Integer.parseInt(s); //this is line 19
System.out.println(tall[i]);
s = in.readLine();
}
in.close();
我想使用的文件Tall.txt写入其中所含到一个名为高阵列的整数。它这样做在一定程度上,还当我运行它,它会引发以下异常(:
I am trying to use the file "Tall.txt" to write the integers contained in them into the array named "tall". It does this to some extent, but also when I run it, it throws the following exception (:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at BinarySok.main(BinarySok.java:19)
到底为什么它这样做,我怎么去除呢?在我看来,我读了文件作为字符串,然后将其转换为整数,这是不是非法的。
Why exactly does it do this, and how do I remove it? As I see it, I read the file as strings, and then convert it to ints, which isn't illegal.
推荐答案
您可能想要做这样的事情(如果你在Java 5和以上)
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
这篇关于Java的:读从文件整数到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文