0

所以我需要做的是将一个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;
}

但我也不太确定,它们都工作得很好,所以我真正要问的是,你会怎么做?

编辑:这个项目不能真正使用外部库。

4

0 回答 0