从文件中收集整数 - Java [英] Collect integers from a file - Java

查看:53
本文介绍了从文件中收集整数 - 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]

推荐答案

有几个问题正如评论中提到的那样,你不是在检查数组边界,而是在逐个字符地阅读。你可能想要查看BufferedReader类。它允许你一次读取整行你也可能想要查看各种原始类型的parse()方法.Number类有一个解析方法,而且周四那么Double,Integer,Long,Short等类也是如此。最后,查看java.util包。它有许多有用的集合,如列表,字典(称为地图)和其他东西。



这里有一些代码可以演示上述所有内容来解决问题你有。



There are a few problems with your code. As has been mentioned in the comments, you're not checking for array bounding and you're reading character by character. You may want to look into the BufferedReader class. It allows you to read an entire line in one go. You also may want to look into the parse() method of the various primitive types. The Number class has a parse method, and thus so do the Double, Integer, Long, Short, etc classes. Last, check out the java.util package. It has a lot of usefully collections such as lists, dictionaries (called Maps), and other things.

Here's some code that demonstrates all of the above to solve the problem you're having.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆