How to save an Arraylist to file?

南笙酒味 提交于 2019-12-13 08:25:04

问题


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){}
}
}

回答1:


Saving an arraylist or any Object could be done like this

      try
      {
         FileOutputStream fileOut =
         new FileOutputStream(filepath);
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(arraylist);
         out.close();
         fileOut.close();
      }
      catch(IOException i)
      {
          i.printStackTrace();
      }



回答2:


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.




回答3:


Write or read a ArrayList in a file can be done by :

  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();
}

}

You will get the answer here.



来源:https://stackoverflow.com/questions/19743195/how-to-save-an-arraylist-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!