java从文本文件读取整数

java从文本文件读取整数,java,inputstream,Java,Inputstream,我正在使用eclipse;我需要从一个文本文件中读取整数,该文件可能有许多行数字,以空格分隔:71 57 99。。。 我需要将这些数字设置为71和57…但我的代码生成的数字范围为10到57 int size = 0; int[] spect = null; try { InputStream is = this.getClass().getResourceAsStream("/dataset.txt"); size = is.availab

我正在使用eclipse;我需要从一个文本文件中读取整数,该文件可能有许多行数字,以空格分隔:71 57 99。。。 我需要将这些数字设置为71和57…但我的代码生成的数字范围为10到57

    int size = 0;
    int[] spect = null;
    try {
        InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
        size = is.available();
        spect = new int[size];
        for (int si = 0; si < size; si++) {
            spect[si] = (int) is.read();//   System.out.print((char)is.read() + "  ");
        }
        is.close();
    } catch (IOException e) {
        System.out.print(e.getMessage());
    }
int size=0;
int[]spect=null;
试一试{
InputStream is=this.getClass().getResourceAsStream(“/dataset.txt”);
size=is.available();
spect=新的整数[大小];
用于(int-si=0;si
读取单个
字节
,然后将其转换为
int
值,您需要使用
BufferedReader
逐行读取,然后使用
split()
Integer.parseInt()
您考虑过使用扫描仪来执行此操作吗?扫描器可以将文件名作为参数,并且可以轻松地读出每个数字

InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
int[] spect = new int[is.available()];
Scanner fileScanner = new Scanner("/dataset.txt");

for(int i = 0; fileScanner.hasNextInt(); i++){
    spect[i] = fileScanner.nextInt();
}

您可以将其转换为
BufferedReader
并读取和拆分行

BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null) {
    String[] strings = line.split(" ");
    for (String str : strings) {
         Integer foo = Integer.parseInt(str);
         //do what you need with the Integer
    }
}

没有人说每对数字之间都有新行,但它不需要有新行。问题是它们之间有一个空格,所以我使用了
line.split(“”
)。但是如果输入文件中有多行,while循环中的
br.readLine()
将处理。这表示bufferredreader没有接受is:inputstram的构造函数"0 71 97 99 103 113 113 114 115 131 137 196 200 202 208 214 226 227 228 240 245 299 311 311 316 327 337 339 340 341 358 408 414 424 429 436 440 442 453 455 471 507 527 537 539 542 551 554 556 566 586 622 638 640 651 653 657 664 669 679 685 735 752 753 754 756 766 777 782 782 794 848 853 865 866 867 879 885 891 893 897 956 962 978 979 980 980 990 994 996 1022 1093“@kobosh我不明白你为什么要发布你文件的内容。它与我发布的新代码一起工作吗?这是全零返回。我刚刚注意到代码中有一个错误。你是否捕捉到它并自行修复?如果没有,可能值得再试一次。