【发布时间】:2015-09-22 11:59:13
【问题描述】:
希望您能提供帮助。仍然试图让我的头脑围绕java!
我有一个文本文件的内容,我想将其存储(并稍后使用)到一个二维数组列表中。 文本文件示例看起来像这样(不确定数量的行上的不确定数量的条目):
狗,猫,猴子,大象
芯片、香肠、豆类、鼠标、蚂蚁
任何东西,无论如何,一些对象,不知道,每一行都有不同的值数
我希望能够按原样打印出文本文件,但项目整齐地存储在我的二维数组列表 (biD)
例如:
狗|猫|猴子|大象|
薯片|香肠|豆类|老鼠|蚂蚁|
any|whatever|some object|dunno|每一行都有不同的|值的数量|
但是当我运行下面的程序时,我得到:
col 是 15
dog|cat|monkey|elephant|chip|sausage|beans|mouse|ant|anything|whatever|some object|dunno|每一行都有不同的|值的数量|
dog|cat|monkey|elephant|chip|sausage|beans|mouse|ant|anything|whatever|some object|dunno|每一行都有不同的|值的数量|
dog|cat|monkey|elephant|chip|sausage|beans|mouse|ant|anything|whatever|some object|dunno|每一行都有不同的|值的数量|
即txt 文件中的每一行(在这种情况下有 3 行)似乎在 biD 结构中产生一个条目,其中包含 txt 文件中的所有行。 真的,每一行打印的应该只包含 txt 文件中的一行项目。
代码如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class testData {
private static Scanner file;
static int rows;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<ArrayList<String>> biD = new ArrayList<ArrayList<String>>();
file = new Scanner(new File("C:/tmp/text.txt"));
ArrayList<String> line = new ArrayList<String>();
while (file.hasNextLine()) {
final String nextLine = file.nextLine();
final String[] items = nextLine.split(",");
for (int i = 0; i < items.length; i++) {
line.add(items[i]);
}
biD.add(line);
rows++;
Arrays.fill(items, null); // to clear out the 'items' array
}
int col = biD.get(0).size();
System.out.println("col is " + col);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < biD.get(i).size(); j++) {
System.out.print(biD.get(i).get(j) + "|");
}
System.out.println();
}
}
}
所以基本上我的 biD 结构似乎存储了太多信息。
所以一个演练(我认为)将是:
从文件中读取一行
存储在字符串中 (nextLine)
拆分字符串并将项目存储在字符串数组(项目)中
将项目添加到数组列表(行)
将该 arraylist 添加到 arraylist biD。
(我认为这是我出错的地方。我认为可能不理解数组列表如何正常工作!)
任何想法,任何人?
谢谢。
【问题讨论】: