我有一个读入的文本文件。它的分隔符是 <.>
。有一个主要主题,然后有三个段落。可以说title
, section1
, section2
, section3
,然后下一篇文章。
如何存储数据,以便 ArrayList 1 具有所有标题,ArrayList 2 具有所有section1信息等?我希望能够输出这些数组。
例如:
大 Storm 即将来临。
关于大 Storm
Storm 静态
关于 Storm 的结论
上面的示例显示了一条记录的样子。
public void read()
{
try
{
FileReader fr = new FileReader(file_path);
BufferedReader br = new BufferedReader(fr);
String s = "";
// keep going untill there is no input left and then exit
while((s = br.readLine()) != null)
{ }
fr.close();
}
catch (Exception e)
{
System.err.println("Error: read() " + e.getMessage());
}
}
public static void main(String [] args)
{
Reader reader = new ResultsReader("C:/data.txt");
reader.read();
String output = ((ResultsReader)reader).getInput();
String str = "title<.>section1<.>section2<.>";
String data[] = str.split("<.>");
}
我不知道如何将数据存储在单独的 ArrayList 中以便可以遍历它们。
最佳答案
您无法创建数组并将数据放入其中,因为您不知道创建数组有多大。因此,请使用列表,然后在读完文件后将它们转换为数组:
List tilesList = new ArrayList<String>();
// etc.
FileReader fr = new FileReader(file_path);
BufferedReader br = new BufferedReader(fr);
String s = null // I think this should be null, so that if there are no lines,
// you don't have problems with str.split();
while((s = br.readLine()) != null) {
String[] line = str.split("<.>");
tilesList.add(line[1]);
// etc.
}
fr.close();
String[] tiles = tilesList.toArray(new String[tilesList.size()]);
// etc.
关于Java读入一个文本文件,然后分成单独的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10575439/