如何将句子中的每个单词放入csv文件中的2d数组中



我试图读取一个文本文件,将每个逗号分隔的值放在一个数组中,并将所有值放在2d数组中。但我现在的代码把整行都放在阵列中

Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
int rows = 3;
int columns = 1;
String[][] myArray = new String[rows][columns];
while (sc.hasNextLine()) {
for (int i = 0; i < myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" " + ",");
for (int j = 0; j < line.length; j++) {
myArray[i][j] = line[j];
}
}
}
System.out.println(Arrays.deepToString(myArray));

这是文本文件:

A6,A7
F2,F3
F6,G6

输出

[[A6,A7], [F2,F3], [F6,G6]]

预期输出

[[A6],[A7],[F2],[F3],[F6],[G6]]

问题是分配整个2D数组,而不是仅分配每个项。

这里有几个备选方案。

  • 使用Files.lines流式传输文件
  • 逗号上的拆分为每行创建两个元素的1D数组
  • CCD_ 3,用于流式传输每个项目
  • 该CCD_ 4对应于一个项目的数组
  • 然后将它们存储在2D阵列中
String[][] array = null;
try {
array = Files.lines(Path.of("f:/MyInfo.txt"))
.flatMap(line->Arrays.stream(line.split(","))
.map(item->new String[]{item}))
.toArray(String[][]::new);
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (array != null) {
System.out.println(Arrays.deepToString(array));
}

打印

[[A6], [A7], [F2], [F3], [F6], [G6]]

这里有一个类似于你的方法。

List<String[]> list = new ArrayList<>();
try {
Scanner scanner = new Scanner(new File("f:/MyInfo.txt"));
while (scanner.hasNextLine()) {
String[] arr = scanner.nextLine().split(",");
for (String item : arr) {
list.add(new String[]{item});
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}

Lists没有deepToString,因此您可以对其进行迭代或转换为2D数组。

String[][] ar = list.toArray(String[][]::new);
System.out.println(Arrays.deepToString(ar));

打印

[[A6], [A7], [F2], [F3], [F6], [G6]]

我认为你必须将行大小增加一倍,每行只放一个元素,并增加i++

结果数组的声明不正确。

由于您希望最终结果应该是这样的,[[A6],[A7],[F2],[F3],[F6],[G6]],它是一个包含一行六列的二维数组。

考虑到这一点,我已经更改并简化了您的代码。

int rows = 3;
String[][] r = new String[1][rows * 2];
FileInputStream fstream = new FileInputStream("/path/to/the/file") 
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while((line = br.readLine()) != null) {
String[] current = line.split(",");
r[0][i++] = current[0];
r[0][i++] = current[1];
}

最新更新