如何将 Arraylist 保存到文件? [英] How to save an Arraylist to file?
本文介绍了如何将 Arraylist 保存到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将数组列表写入文件.但我不知道怎么做.也许你可以帮助我.如何将其保存到文件中?到目前为止代码还好吗?也许你有足够的时间来浏览它.非常感谢,文岑兹
I want to write the arraylist to a file. But I don't know how. Maybe you can help me. How can I save it to a File? And is the code good so far? Maybe you've enough time to look through it. Thanks a lot, Vinzenz
public class SongsManager {
final String MEDIA_PATH = Environment.getExternalStorageDirectory()
.getPath() + "/";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";
private String mp4Pattern = ".mp4";
private String MP3Pattern = ".MP3";
private String MP4Pattern = ".MP4";
// Constructor
public SongsManager() {
}
/**
* Function to read all mp3 files and store the details in
* ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList() {
System.out.println(MEDIA_PATH);
if (MEDIA_PATH != null) {
File home = new File(MEDIA_PATH);
File[] listFiles = home.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
System.out.println(file.getAbsolutePath());
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
// return songs list array
return songsList;
}
private void scanDirectory(File directory) {
if (directory != null) {
File[] listFiles = directory.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
}
private void addSongToList(File song) {
if (song.getName().endsWith(mp3Pattern) || song.getName().endsWith(mp4Pattern) || song.getName().endsWith(MP4Pattern) || song.getName().endsWith(MP3Pattern)) {
HashMap<String, String> songMap = new HashMap<String, String>();
songMap.put("songTitle",
song.getName().substring(0, (song.getName().length() - 4)));
songMap.put("songPath", song.getPath());
// Adding each song to SongList
songsList.add(songMap);
}
}
private void saveFiletoTXT() {
try{
java.io.FileOutputStream fos = new java.io.FileOutputStream("/sdcard/");
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(fos);
oos.writeObject((java.util.ArrayList) songsList);
oos.flush();
fos.close();
}
catch(Exception e){}
}
}
推荐答案
虽然您实际上可以序列化
ArrayList
,但我真的不认为您想要这样做.我认为使用 android.database.sqlite 包
将其内容存储在 SQLLite 中更有意义,如此处.
While you could literally serialize
an ArrayList
, I really don't think you want to do that. I think it makes more sense to store its contents in SQLLite using the android.database.sqlite package
as described here.
这篇关于如何将 Arraylist 保存到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文