有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中读取文件并将其存储在数组中

我想读取一个文本文件并将其存储为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
            }

        }

但我无法将其存储在数组中,因为我得到了空指针异常。如何克服这个问题


共 (2) 个答案

  1. # 1 楼答案

    由于数组“d”为空,因此获取NullPointer:

    String[][] d=null;
    

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

    String[][] d= new String [counterCol][counterRow];
    
  2. # 2 楼答案

    这里有很多错误:

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

    在这里,使用Java Collections将对您有所帮助。特别是^{}

    试一试这样的东西:

    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
            }