【问题标题】:How to read a file and store it in array in java如何读取文件并将其存储在java中的数组中
【发布时间】:2013-11-19 02:39:58
【问题描述】:

我想读取一个文本文件并将其存储为 java 中的字符串多维数组。

输入会是这样的

11 12 13

12 11 16

33 45 6

我想把它存储在

 String[][] as={{"11","12","13"},
       {"12","11","16"},
       {"33","45"}};

我的代码

String file="e:\\s.txt";

         try
       {
       int counterCol=0,counterRow=0;

       String[][] d=null;

       BufferedReader bw=new BufferedReader(new FileReader(file));


        String str=bw.readLine();

        String[] words=str.split(",");

        System.out.println(words.length+"Counterrow");

    counterCol=words.length; //get total words split by comma : column

         while(bw.readLine()!=null)
        {

            counterRow++;    
  // to get the total words as it gives total row count
        }

         String[][] d=new String[counterRow][counterCol];
        for(int x=0;x<counterRow;x++)
        {

            for(int y=0;y<counterCol;y++)
            {

       d[x][y]=bw.readLine();  
   //storing in array. But here gives me the exception
            }

        }

但是当我得到空指针异常时,我无法将它存储在数组中。如何克服这个问题

【问题讨论】:

  • 初始化你的数组 d
  • d[x][y] = new String[counterCol][counterRow];
  • 是的,我已更改并初始化。但我无法存储我的值并取回。获取 null
  • 仅供参考:您的数据示例没有任何逗号。如果文件中的数据相同,那么您将无法使用,因为您正在使用 String[] words=str.split(","); 拆分行

标签: java arrays string store


【解决方案1】:

这里有很多问题:

  1. 数组未初始化
  2. 您没有使用BufferedReader 循环遍历文件行
  3. 您使用逗号而不是示例数据中指定的空格进行分割

使用 Java Collections 将帮助您。特别是ArrayList。

试一试:

String file="e:\\s.txt";

        try {
            int counterRow = 0;

            String[][] d = new String[1][1];

            BufferedReader bw = new BufferedReader(new FileReader(file));

            List<List<String>> stringListList = new ArrayList<List<String>>();

            String currentLine;

            while ((currentLine = bw.readLine()) != null) {
                if (currentLine != null) {
                    String[] words = currentLine.split(" ");
                    stringListList.add(Arrays.asList(words));
                }
            }

            // Now convert stringListList into your array if needed
            d = Arrays.copyOf(d, stringListList.size());

            for (List<String> stringList : stringListList) {

                String[] newArray = new String[stringList.size()];

                for (int i = 0; i < stringList.size(); i++) {
                    newArray[i] = stringList.get(i);
                }

                d[counterRow] = newArray;

                counterRow ++;
            }

        } catch (Exception e) {
            // Handle exception
        }

【讨论】:

    【解决方案2】:

    你得到 NullPointer 因为你的数组 'd' 为空:

    String[][] d=null;
    

    初始化它,它应该可以工作:

    String[][] d= new String [counterCol][counterRow];
    

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 2013-11-19
      • 2023-01-19
      • 2020-04-05
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2020-02-09
      • 2015-02-24
      相关资源
      最近更新 更多