gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:15:38 26 4
gpt4 key购买 nike

我已将网格转换为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com