我有一个数据文件,其中包含5行专辑数据,共有500张专辑。下面的代码将每一行存储为一个新元素,但是我要将 5 行保存为 1 个元素,这可能吗?我将如何更改下面的代码来做到这一点?
String file_name = "Top500Albums.txt";
String line;
ArrayList aList = new ArrayList();
try {
BufferedReader input = new BufferedReader(new FileReader(file_name));
if (! input.ready()){
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
input.close();
}
catch(IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int i=0; i< sz; i++)
{
System.out.println(aList.get(i).toString());
}
最佳答案
您可以像这样将数组列表数据转换为字符串数组
你的数组列表
List<String> list = new ArrayList<String>();
您可以使用toArray()
方法转换为字符串数组
String[] stringArray = list.toArray(new String[0]);
关于java - 如何将 5 行数据作为 1 个元素存储在 ArrayList 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825105/