Java:将文件中的整数读入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/303913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:53:23  来源:igfitidea点击:

Java: Reading integers from a file into an array

javaarraysio

提问by Northener

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();

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 (:

我正在尝试使用文件“Tall.txt”将其中包含的整数写入名为“tall”的数组中。它在某种程度上做到了这一点,但当我运行它时,它也会抛出以下异常(:

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.

为什么它会这样做,我该如何删除它?在我看来,我将文件作为字符串读取,然后将其转换为整数,这并不违法。

回答by erickson

You must have an empty line in your file.

您的文件中必须有一个空行。

You may want to wrap your parseInt calls in a "try" block:

您可能希望将 parseInt 调用包装在“try”块中:

try {
  tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
  continue;
}

Or simply check for empty strings before parsing:

或者在解析之前简单地检查空字符串:

if (s.length() == 0) 
  continue;

Note that by initializing your index variable iinside the loop, it is always 0. You should move the declaration before the whileloop. (Or make it part of a forloop.)

请注意,通过i在循环内初始化索引变量,它始终为 0。您应该在while循环之前移动声明。(或使其成为for循环的一部分。)

回答by Jan Aagaard

It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?

看起来 Java 正在尝试将空字符串转换为数字。在这一系列数字的末尾是否有一个空行?

You could probably fix the code like this

您可能可以像这样修复代码

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

回答by Paul Tomblin

You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.

您可能会混淆不同的行尾。Windows 文件将以回车和换行结束每一行。Unix 上的某些程序会读取该文件,就好像它在每行之间有一个额外的空行,因为它将回车视为行尾,然后将换行视为另一行尾。

回答by Julien Grenier

You might want to do something like this (if you're in java 5 & up)

你可能想做这样的事情(如果你在 java 5 及以上)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
   tall[i++] = scanner.nextInt();
}

回答by Peter Lawrey

For comparison, here is another way to read the file. It has one advantage that you don't need to know how many integers there are in the file.

为了比较,这里是另一种读取文件的方法。它的一个优点是您不需要知道文件中有多少个整数。

File file = new File("Tall.txt");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\s+");
int[] tall = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++) 
    tall[i] = Integer.parseInt(valueStr[i]);
System.out.println(Arrays.asList(tall));

回答by Ban

File file = new File("E:/Responsibility.txt");  
    Scanner scanner = new Scanner(file);
    List<Integer> integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    System.out.println(integers);