将文件读取到2d数组列表中并将每个数据行存储到数组列表中
问题描述:
我想要做的是,在一行中读取多个单词的文件,然后将每个单词添加到2d数组列表中。这应该是[[凯文,凯文,凯文] [工作,工作,工作]]将文件读取到2d数组列表中并将每个数据行存储到数组列表中
下面的代码运作良好,但它确实如此[[kevin,kevin,kevin,jobs,jobs,jobs]]
它应该通过使用嵌套的,但可以有人请帮助吗?
public void getReference() throws IOException
{
String line=null;
connectRead("computer");
//this is a method that reads a file in a format kevin kevin kevin kevin
try
{
reference.add(new ArrayList<String>());
while ((line=bufferedReader.readLine())!=null)
{
st = new StringTokenizer(line);
for (int i = 0 ; i < st.countTokens() ; i++)
{
reference.get(i).add(st.nextToken());
reference.get(i).add(st.nextToken());
reference.get(i).add(st.nextToken());
reference.get(i).add(st.nextToken());
}
}
System.out.println(reference);
bufferedReader.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
文本文件看起来像这样
凯文美国黑客 沃兹尼亚克美国黑客 工作美国黑客
答
您时刻references.get(I),其中i = 0,所以无论何时读取新行,都会从位于第零个索引处的ArrayList开始插入标记。
试试这个,但是这个结构看起来有点让我困惑。可能会显示输入文件的结构有助于更好地编写代码。
public void getReference() throws IOException
{
String line=null;
connectRead("computer");
//this is a method that reads a file in a format kevin kevin kevin kevin
try
{
reference.add(new ArrayList<String>());
int indexOfReferences =0 ;
while ((line=bufferedReader.readLine())!=null)
{
st = new StringTokenizer(line);
for (int i = 0 ; i < st.countTokens() ; i++)
{
reference.get(indexOfReferences).add(st.nextToken());
}
indexOfReferences++;
}
System.out.println(reference);
bufferedReader.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
@ user1105793有一些变化,我编辑了代码。 – Zohaib 2011-12-19 12:11:42
更改代码“线程中的异常”main“java.lang.IndexOutOfBoundsException:Index:1,Size:1”后出现此错误 – Milan 2011-12-19 12:23:30
感谢您的帮助我修复了它 – Milan 2011-12-19 12:28:21