将CSV加载到多维数组中

时间:2013-10-19 15:45:48

标签: java arrays csv

所以我需要做的是将csv文件加载到具有动态数组的JTable(2到6个值之间),首先我提出了这个解决方案:

private String[][] Load()
{
    try {
        final BufferedReader br = new BufferedReader(new FileReader("FilePath");
        try{
            String line;
            final ArrayList<String> List1 = new ArrayList<String>();
            final ArrayList<String> List2 = new ArrayList<String>();
            final ArrayList<String> List3 = new ArrayList<String>();
            while((line = br.readLine()) != null)
            {
                final String[] parse = line.split(",");
                List1.add(parse[0]);
                List2.add(parse[1]);
                List3.add(parse[2]);
            }

            final ArrayList[] lists = new ArrayList[]{List1, List2, List3};
            final String[][] temp = new String[List1.size()][List1.get(0).split(",").length];

            for(int x = 0 ; x < temp.length ; x++)
            {
                for(int y = 0 ; y < temp[x].length ; y++)
                {
                    temp[x][y] = (String) lists[y].get(x);
                }
            }
            return temp;
        }finally
        {
            br.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

我认为这很可怕,所以我提出了这个解决方案:

private String[][] Load()
{

    try
    {
        final BufferedReader br = new BufferedReader(new FileReader("FilePath"));
        try
        {
            final List<String> raw = new ArrayList<String>();
            String line;
            while((line = br.readLine()) != null)
                raw.add(line);

            final String[][] temp = new String[raw.size()][raw.get(0).split(",").length];
            for(int x = 0 ; x < raw.size() ; x++)
            {
                final String[] parse = raw.get(x).split(",");
                for(int y = 0 ; y < temp[x].length ; y++)
                {
                    temp[x][y] = parse[y];
                }
            }
            return temp;
        }finally
        {
            br.close();
        }
    }catch(IOException e){
        e.printStackTrace();
    }
    return null;
}

但是我也不太确定,他们两个都工作得很好,所以我真的都在问,你会怎么做?

编辑:无法在此项目中使用外部库。

0 个答案:

没有答案