如txt文件中有1 2 3
4 5 6
7 8 9 写详细点就是1空格2空格3换行回车
4空格5空格6换行回车
7空格8空格9换行回车或者是4行4列,5行5列,.......都有可能怎么用java把文本文件中,未知多少行列的数组写入到二维数组中呢?谢谢

解决方案 »

  1.   

    package test;import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;public class Client {    static List<List<String>> list = new ArrayList<List<String>>();    static BufferedReader bf = null;    static int length = 0;    public static void main(String[] args) {
            try {
                bf = new BufferedReader(new FileReader(new File("E:\\test.txt")));
                try {
                    write();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String[][] array = new String[length][list.size()];
                for (int i = 0; i < list.size(); i++) {
                    List<String> l2 = list.get(i);                for (int j = 0; j < l2.size(); j++) {
                        array[i][j] = l2.get(j);
                    }
                }
                for (int i = 0; i < array.length; i++) {
                    for (int j = 0; j < array[i].length; j++) {
                        System.out.print(array[i][j]);
                        if (j != array[i].length - 1)
                            System.out.print(",");
                    }
                    System.out.println();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }    static void write() throws IOException {
            String s = null;
            while ((s = bf.readLine()) != null) {
                String[] ss = s.split("\\s+");
                length = ss.length;
                list.add(Arrays.asList(ss));
            }
        }
    }