【问题标题】:Java read from file and store only integers in two arraysJava 从文件中读取并仅将整数存储在两个数组中
【发布时间】:2015-06-06 08:43:50
【问题描述】:

我有这种方法,它只从文件中读取数字并将其存储到两个不同的数组列表中,每行一个。它将行存储为字符串,因此它只有一个索引。

如何从文件中读取并分隔所有数字,以便获得索引 0-14,因为我需要它们稍后进行计算?

该文件包含以下内容:

vot1:8,8,9,1,7,6,8,8,9,5,6,8,7,9,8 
vot2:7,8,8,8,9,4,7,8,10,7,8,9,8,8,9

我的代码是这样的:

public void readFileTest(String path) throws FileNotFoundException {
    BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader(path));

        String line = null;
        int x=0;

        while ((line = br.readLine()) != null) {
            x++;
            if (x<2){
            line = line.substring(line.indexOf(":") + 1); 
            numbers.addAll(Arrays.asList(line.split(",")));
            }else{
            line = line.substring(line.indexOf(":") + 1); 
                numbers1.addAll(Arrays.asList(line.split(",")));
            }

        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    } catch (IOException ex) {
        System.err.println(ex);
    } finally {
        try {
            br.close();
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }

    for (Object c : numbers) {
        System.out.print(c);
    }
    System.out.println();
    for (Object c : numbers1) {
        System.out.print(c);
    }
}

【问题讨论】:

标签: java arrays file


【解决方案1】:

使用numbers.addAll(Arrays.asList(line.split(",")))

【讨论】:

  • 它给了我这个:889176889568798,它没有将它们分开
  • 你能贴出你试过的代码吗??? String.split() 函数返回一个数组而不是一个串联。
  • 这是因为您打印它的方式...System.out.print(c); 一个一个地打印每个元素...所以看起来像这样...数组仍然具有单独的所有数字.. .
  • 好的,很好。那我现在就试试算了
猜你喜欢
  • 1970-01-01
  • 2015-01-22
  • 2023-01-19
  • 1970-01-01
  • 2013-11-19
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多