Saving/Loading HashMap

Discussion in 'Plugin Development' started by nomaf, Jan 24, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    nomaf

    I need help... again...

    I have class for saving objects to file (by Tomsik68). I can save, but I can not load any HashMaps.
    I did test:
    1. Save object (String).
    2. Load object.
    3. Print result.
    4. I gained correct result.
    But I can't still save HashMap.

    My HashMap:
    Code:
    private Map<Player, Boolean> canRef = new HashMap<Player, Boolean>();
    These are save and load methods:
    Show Spoiler
    Code:
    package com.nomaf.refferal.libs;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
     
    /** SLAPI = Saving/Loading API
     * API for Saving and Loading Objects.
     * @author Tomsik68
     */
    public class SLAPI
    {
        public static void save(Object obj, File file) throws Exception
        {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file, true));
            oos.writeObject(obj);
            oos.flush();
            oos.close();
        }
        public static Object load(File file) throws Exception
        {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            Object result = ois.readObject();
            ois.close();
            return result;
        }
    }
     
  2. You can't save a Player object, as it is not serializable (like most Bukkit stuff).
    If you want to save specific data, make your own class using only primitive data types.
    If you only need the player's name, save the player name as String in your hashmap.
     
  3. Offline

    Technius

    Save the objects like this:
    Player's name, true/false

    It could for for multiple entries, like this:
    Code:
    Technius, true
    Player, false
    Not_A_Real_Player, true
    
    Use BufferedWriter and BufferedReader to do this.

    Writing:
    Code:java
    1.  
    2. HashMap<String,Boolean> hashmap = new HashMap<String, Boolean>();
    3. File file = //your file
    4. try
    5. {
    6. for(String p:hashmap.keySet())
    7. {
    8. bw.write(p + "," + hashmap.get(p));
    9. bw.newLine();
    10. }
    11. bw.flush();
    12. bw.close();
    13. }
    14.  


    Reading:
    Code:java
    1.  
    2. HashMap<String, Boolean> hashmap = new HashMap<String, Boolean>();
    3. File file = //your file
    4. try
    5. {
    6. String l;
    7. while((l = br.readLine()) != null)
    8. {
    9. String[] args = l.split("[,]", 2);
    10. if(args.length != 2)continue;
    11. String p = args[0].replaceAll(" ", "");
    12. String b = args[1].replaceAll(" ", "");
    13. if(b.equalsIgnoreCase("true"))hashmap.put(p, true);
    14. else hashmap.put(p, false);
    15. }
    16. br.close();
    17. }
     
  4. Offline

    edocsyl

    What for a Exeption with catch?

    Edit: Got it

    Code:
    catch (IOException e){
                log.info("[ServerNews] + '" + getDataFolder().getPath() + "/player_toggle.yml' not found.");
            }
    
     
  5. Offline

    uruhax

    I don't see any problem with saving or loading for a hashmap in that code. I use almost the same thing on one of my plugins and it works perfectly. Do you get any exception when saving or loading? Or does the file just end up empty?
     
  6. Offline

    edocsyl

    Couldn't run it without exeption. There was an error.
    But there is an other problem..
     
  7. Offline

    nomaf

    Pandemoneus
    Not good. I think about do a new class which implements Player, but Technius idea works ;)

    Technius
    Thx for code!

    edocsyl uruhax
    I haven't any errors. Pandemoneus tells "You can't save a Player object, as it is not serializable (like most Bukkit stuff)."
    As I see Player class doesn't implements Serializable.
     
  8. Offline

    edocsyl

    It works..

    To check if player toggle true / false

    Code:java
    1.  
    2. if (hashmap.containsKey(e.getPlayer().getName())){
    3. if(hashmap.containsValue(true)){
    4.  
    5. //Do domething when it's true
    6. }
    7. }
    8.  


    Toggle:
    Code:java
    1.  
    2. public void toggleJoinNews(String p, CommandSender sender){
    3. if(hashmap.containsKey(p)){
    4. if(hashmap.get(p)){
    5. hashmap.put(p, false);
    6.  
    7. sender.sendMessage(ChatColor.GREEN + "[SN] " + ChatColor.WHITE + "You never get the news on join.");
    8. } else {
    9. hashmap.put(p, true);
    10. sender.sendMessage(ChatColor.GREEN + "[SN] " + ChatColor.WHITE + "You now get the news on join.");
    11.  
    12. }
    13. } else {
    14. hashmap.put(sender.getName(), defaultboolean); //If you want plugin enabled by default change this value to false.
    15. sender.sendMessage(ChatColor.GREEN + "[SN] " + ChatColor.WHITE + "You now get the news on join.");
    16. }
    17. }
    18.  



    Btw: How can u show the code in java ??
     
  9. Code:
    [syntax=java][/syntax]
     
    edocsyl likes this.
  10. Offline

    SgtStud

    Sorry to revive an old thread, but I am doing the same exact thing. Would someone mind explaining this to a noob? Im trying to save

    Code:JAVA
    1. Public Map<Player,Integer> Map1 = new HashMap <Player, Integer>();
    2. Public Map<Player,Integer> Map2 = new HashMap <Player, Integer>();
     
  11. SgtStud You can't save the Player object, because it is not serializable (cannot be written to a file). Try using a HashMap <String, Integer>() and get the player's name. Use the SLAPI from the BukkitWiki also.
     
  12. Offline

    emoknight

    can load Location from hashmap?
     
  13. Offline

    wirher

    Guys, do not store players as it changes a lot. Always store names and use bukkut methods to get player.
     
  14. Offline

    RLS0812

    Always save players, locations, and other non-staralizable things as a string.
     
  15. Offline

    BlueMustache

    Very helpful.
    Thanks guys!
     
  16. Offline

    viper_monster

  17. Offline

    BlueMustache

    And your problem is?
     
  18. Offline

    viper_monster

    BlueMustache you are bumping a 2 years old thread just to say it helped you, that's my problem.
     
  19. Offline

    SuperOmegaCow

    spoljo666 BlueMustache lololololol

    nomaf should probably put this as solved.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 23, 2016
  20. Offline

    BlueMustache

    Is that a crime against humanity?
     
  21. Offline

    viper_monster

    BlueMustache of course it is! I will inform the European Court of Human Rights about this...
     
  22. Offline

    BlueMustache

    Fine then.
    Be that guy.
     
  23. Offline

    Monkeyboystein

    Dont be that guy, that brings up that guy, ya know guy?
     
  24. Offline

    BlueMustache


    #oldthreads
     
  25. Offline

    SuperOmegaCow

Thread Status:
Not open for further replies.

Share This Page