在Java中将文本文件转换为二维不规则数组

时间:2009-11-12 22:37:48

标签: java arrays string file arraylist

嘿伙计们,这是对my previous question的跟进。我现在有一个文本文件格式如下:

100 200
123
124 123 145

我想要做的是将这些值放入Java中的二维不规则数组中。 到目前为止我所拥有的是:

public String[][] readFile(String fileName) throws FileNotFoundException, IOException {
       String line = "";
       ArrayList rows = new ArrayList();


       FileReader fr = new FileReader(fileName);
       BufferedReader br = new BufferedReader(fr);

       while((line = br.readLine()) != null) {
        String[] theline = line.split("\\s");//TODO: Here it adds the space between two numbers as an element
        rows.add(theline);
       }
       String[][] data = new String[rows.size()][];
       data = (String[][])rows.toArray(data);
       //In the end I want to return an int[][] this a placeholder for testing
       return data;

我的问题是,例如对于100 200行,变量“theline”有三个元素{"100","","200"},然后传递给rows.add(theline)的行 我想要的只是数字,如果可能的话,如何将这个String [] []数组转换为int [] []数组,最后返回它。 谢谢!

4 个答案:

答案 0 :(得分:2)

如果您使用Scanner类,则可以继续调用nextInt()

例如(这是p代码......你需要清理它)

scanner = new Scanner(line);
while(scanner.hasNext())
  list.add(scanner.nextInt())
row = list.toArray()

这当然也没有得到很好的优化。

答案 1 :(得分:1)

而不是使用.split(),您可以尝试使用StringTokenizer将您的行拆分为数字

答案 2 :(得分:0)

我尝试时你的解析工作正常。 两个

 line.split("\\s");

 line.split(" ");

将样本数据拆分为正确数量的字符串元素。 (我意识到“\ s”版本是更好的方法)

这是一种将数组转换为int数组的强力方法

int [][] intArray = new int[data.length][];
for (int i = 0; i < intArray.length; i++) {
    int [] rowArray =  new int [data[i].length];
    for (int j = 0; j < rowArray.length; j++) {
        rowArray[j] = Integer.parseInt(data[i][j]);
    }
    intArray[i] = rowArray;
}

答案 3 :(得分:0)

好的,这是基于Gonzo建议的解决方案:

public int[][] readFile(String fileName) throws FileNotFoundException, IOException {
   String line = "";
   ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();


   FileReader fr = new FileReader(fileName);
   BufferedReader br = new BufferedReader(fr);

   int r = 0, c = 0;//Read the file
   while((line = br.readLine()) != null) {
       Scanner scanner = new Scanner(line);
       list.add(new ArrayList<Integer>());
       while(scanner.hasNext()){

           list.get(r).add(scanner.nextInt());
           c++;
       }
       r++;
   }

   //Convert the list into an int[][]
   int[][] data = new int[list.size()][];
   for (int i=0;i<list.size();i++){
       data[i] = new int[list.get(i).size()];
      for(int j=0;j<list.get(i).size();j++){
          data[i][j] =  (list.get(i).get(j));
      }


   }
   return data;
}