Thi*_*mer 1 java nested arraylist nested-class text-files
因此,对于我正在处理的程序,我正在尝试创建一个解析文本文件的方法.使用文本文件中的值,创建一个ArrayList内ArrayList.到目前为止,这是我的代码:
public ArrayList<ArrayList<String>> getRels(String relsFile)
{
String[] currentId;
int i = -1;
ArrayList<ArrayList<String>> relsList = new ArrayList<ArrayList<String>>();
relsList.add(new ArrayList<String>());
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(relsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null)
{
// Add values to array list
currentId = strLine.split(",");
relsList.get(++i).add(currentId[0]);
//???????????
}
//Close the input stream
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
return relsList;
}
Run Code Online (Sandbox Code Playgroud)
这是我正在查看的文本文件的示例.
rId13,image3
rId18,image8
rId26,image16
rId39,image29
rId21,image11
rId34,image24
rId7,image1
rId12,image2
rId17,image7
rId25,image15
rId33,image23
rId38,image28
rId16,image6
rId20,image10
rId29,image19
rId24,image14
rId32,image22
rId37,image27
rId15,image5
rId23,image13
rId28,image18
rId36,image26
rId19,image9
rId31,image21
rId14,image4
rId22,image12
rId27,image17
rId30,image20
rId35,image25
Run Code Online (Sandbox Code Playgroud)
本质上,我希望能够分割值,将所有rId值存储在第一个值中ArrayList,然后image在嵌套中列出它们的相应值ArrayList.但是,我有点卡住,不知道该做什么.有人可以帮帮我吗?我感谢所提供的任何帮助.
我建议你使用调试器来查看到底发生了什么.
从读取代码我猜它会读取第一行没关系,但在那之后失败,因为你只添加一个嵌套的ArrayList但尝试使用其中的许多.
最简单的方法是返回Map <String,String>,因为我假设第一列是唯一的.
public static Map<String, String> getRels(String relsFile) {
Map<String, String> map = new LinkedHashMap<String, String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(relsFile));
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(",", 2);
if (parts.length > 1)
map.put(parts[0], parts[1]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ignored) {
}
}
return map;
}
Run Code Online (Sandbox Code Playgroud)