Saving a Hash Map

Discussion in 'Plugin Development' started by Tehepicford, Aug 19, 2012.

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

    Tehepicford

    OK, I'm having another problem ;P
    When I reload my server. The Hash Map shall not save. Nor load.
    Yes, I've tried to. Here is what I have so far.

    Code:
    package com.fordnatford.ForceRules;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.util.HashMap;
    import java.util.logging.Logger;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Main extends JavaPlugin {
        public static HashMap<String, Boolean> hasAcceptedRules = new HashMap<String, Boolean>();
        public final Logger logger = Logger.getLogger("Minecraft");
        public static Main plugin;
        public final BukkitListner bl = new BukkitListner(this);
     
    public void onDisable() {
        PluginDescriptionFile pdfFile = this.getDescription();
        this.logger.info(pdfFile.getName() + " Has been disabled!");
        save(hasAcceptedRules, getDataFolder() + File.separator + "ForecRules.bin");
     
    }
     
    public void onEnable() {
        PluginDescriptionFile pdfFile = this.getDescription();
        this.logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " Has been Enabled!");
        PluginManager pm = this.getServer().getPluginManager();
        pm.registerEvents(bl, this);
        if(file.exists()) {
        hasAcceptedRules  = load(path);
        }
    }
     
     
    String path = getDataFolder() + File.separator + "save.bin";
    File file = new File(path);
    public HashMap<String, Boolean> load(String path)
    {
        try
        {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
            Object result = ois.readObject();
            return (HashMap<String, Boolean>)result;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
     
     
     
    public void save(HashMap<String, Boolean> map, String path)
    {
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
            oos.writeObject(map);
            oos.flush();
            oos.close();
     
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
     
     
     
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        Player player = (Player) sender;
        if(label.equalsIgnoreCase("accept")) {
        hasAcceptedRules.put(player.getName(), true);
        player.sendMessage("Thanks for accepting the rules!");
        }
        return false;
     
    }
     
     
    public void onPlayerJoin(PlayerJoinEvent evt) {
        Player player = evt.getPlayer(); // The player who joined
        if(hasAcceptedRules.containsKey(player)) {
            player.sendMessage("Welcome back " + ChatColor.YELLOW + player.getName());
        }
        else {player.sendMessage("Please read and accept the rules!");}
    }
     
    }

    Again, Help appreciated.

    EDIT:
    I have a folder called 'save.bin' in the Project Workspace, But that is all. Yet again Help Appreciated!
     
  2. Offline

    nala3

    Use a List<String> to see who has accepted. Anyone who is not on the list obviously has not accepted. A hash map is unneeded here.

    To save the file, create a print write and do a for loop through each item in the list and print it to a new line in the file. Then, to load it, read the file line by line putting the string back into the list.

    EDIT: also, do not use Logger.getLogger("Minecraft"). Use this.getLogger();
     
  3. Offline

    Tehepicford

    How do I do that :C?
     
  4. Offline

    nala3

    Look up PrintWriter it's really not hard.
     
  5. Offline

    Tehepicford

    Uhhhhh, Sources?

    http://www.java-samples.com/showtutorial.php?tutorialid=329 Waa?

    Ok, I've got the save code, What about load?
    Also, Could you put this in correct 'terms'

    Code:
    package com.fordnatford.ForceRules;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.logging.Logger;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Main extends JavaPlugin {
        public static HashMap<String, Boolean> hasAcceptedRules = new HashMap<String, Boolean>();
        public final Logger logger = Logger.getLogger("Minecraft");
        public static Main plugin;
        public final BukkitListner bl = new BukkitListner(this);
     
    public void onDisable() {
        PluginDescriptionFile pdfFile = this.getDescription();
        this.logger.info(pdfFile.getName() + " Has been disabled!");
     
    }
     
    public void onEnable() {
        PluginDescriptionFile pdfFile = this.getDescription();
        this.logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " Has been Enabled!");
        PluginManager pm = this.getServer().getPluginManager();
        pm.registerEvents(bl, this);
    }
     
     
    [B]String path = getDataFolder() + File.separator + "save.bin";
    [B]File file = new File(path);
     
    public static void main(String[] args) {
        String filename = "data.txt"; 
        try {
            PrintWriter outputStream = new PrintWriter(filename);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
    }
     
     
     
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        Player player = (Player) sender;
        if(label.equalsIgnoreCase("accept")) {
        hasAcceptedRules.put(player.getName(), Boolean.TRUE);
        player.sendMessage("Thanks for accepting the rules!");
        }
        return false;
     
    }
     
     
    public void onPlayerJoin(PlayerJoinEvent evt) {
        Player player = evt.getPlayer(); // The player who joined
        if(hasAcceptedRules.containsKey(player)) {
            player.sendMessage("Welcome back " + ChatColor.YELLOW + player.getName());
        }
        else {player.sendMessage("Please read and accept the rules!");}
    }
     
    }
    Shoot, I don't read -.-, Thanks.

    Wait what?

    'To save the file, create a print write and do a for loop through each item in the list and print it to a new line in the file. Then, to load it, read the file line by line putting the string back into the list.'

    I'm a Novice at codding c:

    Is bumping aloud? Oh well, Bump.

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

    nala3

    Try this out. No file needed.
    Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
     
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerMoveEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Testing extends JavaPlugin implements Listener {
     
        private Logger log;
        private List<String> notAccepted = new ArrayList<String>();
     
        @Override
        public void onEnable() {
            this.log = this.getLogger();
            this.getServer().getPluginManager().registerEvents(this, this);
        }
       
        private boolean hasAccepted(String name) {
            return !notAccepted.contains(name);
        }
     
        @Override
        public boolean onCommand(CommandSender sender, Command command,
                String label, String[] args) {
            if(!(sender instanceof Player))
                return true;
     
            if(command.getName().equalsIgnoreCase("accept") && !this.hasAccepted(sender.getName())) {
                notAccepted.remove(sender.getName());
                sender.sendMessage(ChatColor.BLUE + "You have accepted the rules and may now play!");
            }
            return true;
        }
       
        @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event) {
            Player p = event.getPlayer();
            if(!p.hasPlayedBefore()) {
                notAccepted.add(p.getName());
                p.sendMessage(ChatColor.RED + "You must accept the rules to play!");
            } else {
                p.sendMessage(ChatColor.YELLOW + "Welcome back, " + p.getName());
            }
        }
       
        @EventHandler
        public void onPlayMove(PlayerMoveEvent event) {
            if(!this.hasAccepted(event.getPlayer().getName())) {
                event.setCancelled(true);
            }
        }
       
    }
     
Thread Status:
Not open for further replies.

Share This Page