本文介绍了从文件中收集整数 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我有一个用PrintWriter类创建的文件,只包含用空格分隔的整数,我为每一行恢复了这些整数并放入在表格中。

例如,如果我有3行,我必须有3张桌子。



[edit]

我的问题是当我这样做时:



Hello,

I have a file created with a PrintWriter class, containing only integers separated by a space, I'd recovered these integers for each line and put in tables.
For example, if I have 3 lines, I must have 3 tables.

[edit]
My problem is when I do:

FileReader fr = new FileReader("path/file.txt");
int[] tab = new int [10];
int i = 0;
int c = fr.read();
while(c != -1){
   if(c != (int)(' '){
      tab[i] = c;
      i++;
   }
   c = fr.read();
}



i有一个例外:java.lang.ArrayIndexOutOfBoundsException,文件不超过10个整数



注意:这里只是在我只有一行的情况下

[/ edit]


i have an exception : java.lang.ArrayIndexOutOfBoundsException, and the file doesn't exceed 10 integers

NB : here it's only in case when I have only one single line
[/edit]

推荐答案

String line = null;
ArrayList<integer> numbers = new ArrayList<>();
//Try-with-resource, so the stream is automatically closed when we're done
try(BufferedReader reader = new BufferedReader(new FileReader("someFilePath"))){
    //While the last line we read is not null, aka EOF
    while((line = reader.readLine()) != null){
        //Split along spaces
        String[] ints = line.split(" ");
        //For each integer in the line
        for(String number : ints){
            try{
                //Try to parse the string into an integer
                Integer i = Integer.parse(number);
                //Add it to the list
                numbers.add(i);
            }
            catch(NumberFormatException ex){
                //Parsing failed, keep going anyway
                continue;
            }
        }
    }
}
catch(IOException ex){
    //TODO Handle exception
}


这篇关于从文件中收集整数 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 14:55