我想将arraylist写入文件。但我不知道怎么做。 也许你可以帮助我。如何将其保存到文件?到目前为止,代码是否良好?也许你有足够的时间来审视它。 非常感谢,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){}
}
}
答案 0 :(得分:2)
可以像这样保存arraylist或任何Object
try
{
FileOutputStream fileOut =
new FileOutputStream(filepath);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(arraylist);
out.close();
fileOut.close();
}
catch(IOException i)
{
i.printStackTrace();
}
答案 1 :(得分:2)
虽然你可以serialize
ArrayList
,但我真的不认为你想这样做。我认为使用here所述的android.database.sqlite package
将其内容存储在SQLLite中会更有意义。
答案 2 :(得分:0)
在文件中写入或读取ArrayList可以通过以下方式完成:
public static void write(Context context, Object nameOfClass) {
File directory = new File(context.getFilesDir().getAbsolutePath()
+ File.separator + "serlization");
if (!directory.exists()) {
directory.mkdirs();
}
String filename = "MessgeScreenList.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(directory
+ File.separator + filename));
out.writeObject(nameOfClass);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
您将得到答案here。