【问题标题】:How to add elements stored in a file to an array?如何将存储在文件中的元素添加到数组中?
【发布时间】:2014-04-07 14:33:41
【问题描述】:

我有一个包含如下数据元素的文件:

1749 12426 19597 38042 43350 52873 67704 75875 81829 96307

11615 16454 20015 27021 52762 66631 70625 83951 96527 96893

3370 5530 28692 39087 50591 59442 61906 69337 70643 91162

1947 4604 9657 16455 21149 22739 32809 66089 73871 97304

3429 5325 7888 24101 28851 31637 32424 57991 62470 65017

我在将文件的每个元素添加到数组的不同索引上时遇到问题。从互联网搜索时,我只能将所有第一行存储在索引数组 [0] 上。 (所有行都存储在索引[0]上)

我要存储所有列元素数组

array[0] = 1749 
array[1] = 11615 
array[2] = 3370
array[3] = 1947
array[4] = 3429

第二遍:

array[0] = 12426
array[1] = 16454
array[2] = 5530 
array[3] = 4604 
array[4] = 5325 

以此类推,直到第 10 遍..... 请对下面给出的代码进行必要的更改:

File            file = new File("SortedLines.txt");
FileInputStream fis  = null;

try {
    fis = new FileInputStream(file);

    int content;

    while ((content = fis.read()) != -1) {
        // convert to char and display it
        System.out.print((char)content);
    }
} catch (IOException e) {
    e.printStackTrace();
} 

【问题讨论】:

  • 所以你会覆盖每个通道中的元素,对吧?
  • PLEASE make necessary changes in the code given below 除了读取文件中的每个字符之外,您的代码与您描述的问题无关。也许先自己尝试一些东西(扫描仪类在这里可能会有所帮助),然后当您得到与预期不同的结果或一些错误时回来。尝试读取每一行,将其拆分为空间并读取您感兴趣的第 n 个元素。
  • 只需将所有行存储在 String ArrayList 中,并使用 String.split() 方法将每个 nos 分开,您将得到每个 no 作为单独的 no 然后添加它们
  • 是的,我想在每遍中重写元素

标签: java arrays file


【解决方案1】:

您应该逐行读取文件 lne,并且对于每一行,用空格分隔将数字添加到数组中:

ArrayList<String> myArray = new ArrayList<String>(0);

//Read File Line By Line
  while ((strLine = br.readLine()) != null)   {

    // split by space
    String[] numbers= strLine.split(" ");

    for(String num numbers){
        myArray.add(strLine);  
    }

  }

【讨论】:

  • 我无法实现它。你能写出确切的代码吗?如果我粘贴你的代码,我会遇到很多错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 2021-12-04
相关资源
最近更新 更多