java - 将 CSV string[] 转换为 string[][]

标签 java csv

我已将网格转换为 CSV 格式,这会将其转换为字符串以保存网格。

但是,当我想打开 CSV 文件时,我必须将字符串转回二维数组。我已经尝试找出如何做到这一点,但我不确定如何连接两个 string[],使其变成二维数组。

我在行结束处添加了一个 ; ,并且必须开始新行,但我对如何将其添加在一起感到困惑。

代码:

public static void open() {
            // The name of the file to open.
            String name = JOptionPane.showInputDialog(null,
                    "Enter the name of the file you wish to open: ");
            String fileName = name+ ".txt";

            // This will reference one line at a time
            String line = null;

            char gridWorld[][];

            try {
                // FileReader reads text files in the default encoding.
                FileReader fileReader = new FileReader(fileName);

                // Always wrap FileReader in BufferedReader.
                BufferedReader bufferedReader = new BufferedReader(fileReader);

                String[] firstsplit, secondsplit;
                while ((line = bufferedReader.readLine()) != null) {
                    for(int i = 0; i < line.length(); i++){
                        firstsplit = line.split(";");   // if semi colon, replace with new line

                    }

                    secondsplit = line.split(","); // splitting the line in columns

                }

                // Always close files.
                bufferedReader.close();

任何帮助将不胜感激。

最佳答案

带有行号和索引的 .csv 文件格式:

       | columnIndex
       | 1 2 3 4 
----------------
line1  | 1,2,3,4
line2  | 5,6,7,8
line3  | 9,a,b,c
...
lineN  | w,x,y,z

通过这个可视化,应该很容易看出如何解析它。这是将其读入 gridWorld 数组的代码片段,希望有所帮助:

lineIndex = 0;
while ((line = br.readLine()) != null) {
    String[] split = line.split(",");
    for (int i=0; i<split.length; i++) {
        gridWorld[lineIndex][i] = split[i].charAt(0);        
    }
    lineIndex++;
}

关于java - 将 CSV string[] 转换为 string[][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21267630/

相关文章:

java - 在 Jmeter 中无法创建 PoolableConnectionFactory

java - YouTube API : Search videos playable on mobile devices

java - 使用单个按钮从另一个 Jlist 填充 Jlist

java - 缩放和加载非常大的 TIFF 文件

python - Django Web 项目中用户提供的 CSV

嵌入式应用程序的 CSV 或二进制文件

python - 如何使用 python 将表中的数据从多行转变成只有 4 行

java - 堆栈跟踪显示错误位置的异常

python - 从 csv 读取后,第一列名称用双引号括起来

Javascript 将 CSV 字符串映射到 JSON 数组