How to load Hashmaps - onEnable?

Discussion in 'Plugin Development' started by recon88, Jun 1, 2012.

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

    recon88

    I can't figure out how to load the saved hashmaps back into the plugin.
    I took this wiki part to start over.
    Saving works. But how to load it? Can someone give me an example for the loading method + onEnable part which will work with my testing code below?
    Btw: I don't use the SLAPI

    The hashmap itself:
    Code:
    HashMap<String, Double> testing = new HashMap<String, Double>();
    onDisable:
    Code:
        public void onDisable() {
            save(testing, "testing.dat");
            PluginDescriptionFile pdfFile = this.getDescription();
            System.out.println("[" + pdfFile.getName() + "] version [" + pdfFile.getVersion() + "] is disabled.");
        }
    save():
    Code:
        public void saveTesting(HashMap<String,Double> testing, String path)
        {
            try{
                ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(path));
                output.writeObject(testing);
                output.flush();
                output.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
     
  2. Offline

    r0306

    recon88
    Create another method (which I named loadData(String string)) that you would call on enable to initialize your hashmap with.
    Code:
        public static HashMap<String,Long> loadData(String path) throws FileNotFoundException, IOException, ClassNotFoundException {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("path to your .bin file"));
                Object result = ois.readObject();
                ois.close();
                return (HashMap<String,Long>)result;
        }
    Then in your onEnable(), add a try/catch statement to call up the method.
    Code:
        public static HashMap<String, Long> YourHashMap = new HashMap<String, Long>();
    public onEnable() {
        try {
            YourHashMap = (HashMap<String, Long>)yourclassname.loadData("YourHashMap.bin");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
              System.out.println("[Plugin] Data file not found. Generating file...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     
  3. Why ? It seems a good enough example and you don't have to keep it inside a separate class, you can just place them in your main code... or is it because of credits ?

    r0306 you didn't close the stream... and you got the exceptions all wrong.... and you shouldn't guide code with try-catch because it's slow.

    Anyway, just do a:
    Code:
    public static void save(Object obj,String path) throws Exception
    {
    	try
    	{
    		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
    		oos.writeObject(obj);
    		oos.flush();
    		oos.close();
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    }
    
    public static Object load(String path) throws Exception
    {
    	try
    	{
    		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
    		Object result = ois.readObject();
    		ois.close();
    		return result;
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    }
    
    
    public void onEnable()
    {
    	String path = getDataFolder() + File.separator + "hashmapfile.whatever";
    
    	File db = new File(path);
    	db.mkdirs(); // you also might want to create your directories if they're not there... I'm unsure if the save method does that tough
    
    	if(db.exists())
    		hashmap = load(path);
    
    	// you don't need to warn when file is missing beacuse you're going to create it when necesairy.
    }
     
  4. Offline

    r0306

  5. Offline

    recon88

    Code:
    03:49:34 [SCHWERWIEGEND] java.io.FileNotFoundException: testing.bin (File not found)
    03:49:35 [SCHWERWIEGEND]        at java.io.FileInputStream.open(Native Method)
    03:49:35 [SCHWERWIEGEND]        at java.io.FileInputStream.<init>(Unknown Source
    )
    03:49:35 [SCHWERWIEGEND]        at java.io.FileInputStream.<init>(Unknown Source
    )
    03:49:35 [SCHWERWIEGEND]        at com.recon.testing.testing.load(testing.java:190)
    03:49:35 [SCHWERWIEGEND]        at com.recon.testing.testing.onEnable(testing.java:68)
    03:49:35 [SCHWERWIEGEND]        at org.bukkit.plugin.java.JavaPlugin.setEnabled(
    JavaPlugin.java:215)
    03:49:35 [SCHWERWIEGEND]        at org.bukkit.plugin.java.JavaPluginLoader.enabl
    ePlugin(JavaPluginLoader.java:337)
    03:49:35 [SCHWERWIEGEND]        at org.bukkit.plugin.SimplePluginManager.enableP
    lugin(SimplePluginManager.java:381)
    03:49:35 [SCHWERWIEGEND]        at org.bukkit.craftbukkit.CraftServer.loadPlugin
    (CraftServer.java:256)
    03:49:35 [SCHWERWIEGEND]        at org.bukkit.craftbukkit.CraftServer.enablePlug
    ins(CraftServer.java:238)
    03:49:35 [SCHWERWIEGEND]        at net.minecraft.server.MinecraftServer.t(Minecr
    aftServer.java:381)
    03:49:35 [SCHWERWIEGEND]        at net.minecraft.server.MinecraftServer.a(Minecr
    aftServer.java:368)
    03:49:35 [SCHWERWIEGEND]        at net.minecraft.server.MinecraftServer.init(Min
    ecraftServer.java:197)
    03:49:35 [SCHWERWIEGEND]        at net.minecraft.server.MinecraftServer.run(Mine
    craftServer.java:432)
    03:49:35 [SCHWERWIEGEND]        at net.minecraft.server.ThreadServerApplication.
    run(SourceFile:492)
    Code:
        public void onEnable() {
                try {
                testing = (HashMap<String, Double>)testing.load("testing.bin");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                  System.out.println("[Plugin] Data file not found. Generating file...");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    Code:
        @SuppressWarnings("unchecked")
        public static HashMap<String,Double> load(String path) throws FileNotFoundException, IOException, ClassNotFoundException {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("testing.bin"));
            Object result = ois.readObject();
            ois.close();
            return (HashMap<String,Double>)result;
        }
    Digi
    Just don't want to use it =)
     
  6. recon88
    Then don't load hashmaps, because there isn't another code :)

    Just google "java hashmaps load from file" and you'll find the same code everywhere, codes that have this:
    Code:
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    ...and this...
    Code:
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
    Object result = ois.readObject();
    ois.close();
    return result;
    ... at their core., which is what r0306 also posted.
    Other details like the try-catch are just that, details.

    Now, your error is self-explainatory... "java.io.FileNotFoundException: testing.bin (File not found)", in my example I check if the file exists.
     
  7. Offline

    recon88

    Wait... Why is his example throwing the exception?
    There's already an try-catch in the onEnable part. :confused:

    Edit:
    nvm... got it
     
  8. Offline

    r0306

    Make sure you defined the right path to your bin file.
     
  9. You never closing the file when something is wrong whit the file writing
    use the try-catch-finaly block for it, or the java 7 try-whit-resources
     
Thread Status:
Not open for further replies.

Share This Page