Saving Data

Discussion in 'Plugin Development' started by Deleted user, Oct 14, 2012.

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

    Deleted user

    Best way of saving / loading (reading) hashmaps?
     
  2. Offline

    Timr

  3. Offline

    Deleted user

    On
    Code:
    list = SLAPI.load("example.bin");
    
    Where it says "example.bin"
    I understand that but are you suppose to manually create the topic and sub topics from the plugin? Because how else would you manually edit a .bin?
     
  4. Offline

    Sagacious_Zed Bukkit Docs

    It is a binary file, get a hex editor if you don't want to do it from code. else move to a text based system such as yaml files with the configuration api
     
  5. Offline

    Deleted user

    I'm getting errors about creating the data.bin file on start up?
     
  6. Offline

    Sagacious_Zed Bukkit Docs

    That's nice. Feel free to tell the world what error you are getting.
     
    ferrybig, zack6849, kroltan and 4 others like this.
  7. Offline

    Karl Marx

  8. Offline

    Technius

    It's quite easy once you understand how to do it.
    First, you want to open a FileWriter or BufferedWriter on the file you want to write to.
    Code:
    try
    {
        File file = new File(getDataFolder(), "data.txt");//This is the file you want to write to
        if(!file.exists())//If the file doesn't exist, make the file
        {
            FileOutputStream fos = new FileOutputStream(file);//Open a new FileOutputStream
            fos.flush();//Save the empty file
            fos.close();//Close the stream
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));//Open a new writer on the file
        for(Map.Entry<String, String> e:yourMap.entrySet())//This is assuming your map is <String, String>
        //It'll be easy if your keys and values are Strings and numbers
        {
            bw.write(e.getKey() + "," + e.getValue());//This will save the data
            //If your key was "a" and your value was "b" it would be saved as "a,b"
            bw.newLine();//Make a new line
        }
        bw.flush();//Save the data
        bw.close();//Close the writer
    }
    catch(IOException ioe)//An error occurred, oh no!
    {
        ioe.printStackTrace();//Print the error log to the console
    }
    
    Next is loading, which can be done by opening a BufferedReader and parsing the lines.
    Code:
    try
    {
        File file = new File(getDataFolder(), "data.txt");//This is the file you want to read from
        if(file.exists())//Your file exists!
        {
            BufferedReader br = new BufferedReader(new FileReader(file));//Create the reader
            String l;//This is the line that the reader will get while reading the file
            while((l = br.readLine() != null)//While the read line is not null
            {
                String[] tokens = l.split(",", 2);//Split the line by a comma, but limit the pieces to 2
                //This means "key,"value"" would be read as key and "value"
                if(tokens.length != 2)continue;//If there is only a key or only a value, skip the line
                yourMap.put(tokens[0], tokens[1]);//Store the data in your map
            }
            br.close();//Close the reader
        }
    }
    catch(IOException ioe)//An error occurred
    {
        ioe.printStackTrace();//Print the error log to the console
    }
    
    Hope that helped!
     
    ZeusAllMighty11 and Timr like this.
  9. Offline

    Deleted user


    I'm getting errors on reading the data.

    My HashMaps are <String, Integer > 's and there are three of them so how do I differ from them and overwrite each other but only the same ones.. also here is my code error.

    Code:
    Type mismatch: cannot convert from boolean to String
    
    Code:java
    1.  
    2.  
    3. while((l = br.readLine() != null)
    4.  
    5.  


    and

    Code:
    The method put(String, Integer) in the type HashMap<String,Integer> is not applicable for the arguments (String, String)
    
    Code:java
    1.  
    2. CCMage.MAGE_LIST.put(tokens[0], tokens[1]);
    3.  


    I'm sorry if I didn't explain my problems thoroughly or as in depth as possible, this whole matter is quite confusing to me.
     
  10. Offline

    TwistedMexi

    I think the main complaint here is you're saying "I'm getting errors" but you're not posting the actual stacktrace (error) here. It's very hard to troubleshoot without it as often times the error tells you exactly where the problem lays.
     
    kroltan likes this.
  11. Offline

    Sagacious_Zed Bukkit Docs

    These are not errors with saving data. These are type errors when you give a method a parameter of the wrong type. They seem to stem from syntax errors
     
  12. Offline

    Deleted user

    Well I've actually gotten it figured out now, I have this:

    Code:java
    1.  
    2. /**
    3. * SLAPI = Saving/Loading API API for Saving and Loading Objects. You can
    4. * use this API in your projects, but please credit the original author of
    5. * it.
    6. *
    7. * @author Tomsik68<[email][email protected][/email]>
    8. */
    9. public static <T extends Object> void save(T obj, String path) throws Exception {
    10. oos.writeObject(obj);
    11. oos.flush();
    12. oos.close();
    13. }
    14.  
    15. public static <T extends Object> T load(String path) throws Exception {
    16. @SuppressWarnings("unchecked")
    17. T result = (T) ois.readObject();
    18. ois.close();
    19. return result;
    20. }
    21.  
    22. public static void saveData() {
    23. File f = new File(CCMain.getInstance().getDataFolder(), "data.bin");
    24.  
    25. try {
    26. if (!f.exists()) {
    27. CCMain.getInstance().getDataFolder().mkdirs();
    28. f.createNewFile();
    29. }
    30. save(CCMage.MAGE_LIST, "plugins/ClassCraft/data.bin");
    31. save(CCPriest.PRIEST_LIST, "plugins/ClassCraft/data.bin");
    32. save(CCWarrior.WARRIOR_LIST, "plugins/ClassCraft/data.bin");
    33. } catch (Exception e) {
    34. e.printStackTrace();
    35. }
    36. }
    37.  
    38. public static void loadData() {
    39. File f = new File(CCMain.getInstance().getDataFolder(), "data.bin");
    40.  
    41. try {
    42. if (!f.exists()) {
    43. return;
    44. }
    45. CCMage.MAGE_LIST = load("plugins/ClassCraft/data.bin");
    46. CCPriest.PRIEST_LIST = load("plugins/ClassCraft/data.bin");
    47. CCWarrior.WARRIOR_LIST = load("plugins/ClassCraft/data.bin");
    48. } catch (Exception e) {
    49. e.printStackTrace();
    50. }
    51. }
    52.  


    However how do I make it save multiple Hashmaps? And allow each hashmap to overwrite itself.
     
  13. Offline

    Sagacious_Zed Bukkit Docs

    SLAPI as it is written here, allows you to write one object per a file. Either encapsulate all your hashmaps into one object or write each hashmap into its own file, or rewrite parts of slapi to allow you to save multiple objects per file.
     
  14. Offline

    Infamous Jeezy

    I always had trouble saving hashmaps as .bin files but maybe it was the types I was trying to save.
    Saving them as .dat files worked great for me.
     
  15. Offline

    Sagacious_Zed Bukkit Docs

    file endings mean nothing to Java, i can give my yaml file .baz or .ser and it would read it quite happily.
     
  16. Offline

    Infamous Jeezy

    oh I see.. when I tried saving it as a .bin I always got errors, but maybe it was just a coincidence. :\
     
  17. Offline

    Deleted user

    Okay then can you help me out man ha? How can I go about writing multiple hashmaps, and other forms of data into one file?
     
  18. Offline

    Sagacious_Zed Bukkit Docs

    If you are going to use slapi, then encapsulate all the data you want to save within one serializable object. If not the Configuration API is more than capable of storing multiple Hashmaps and ConfigurationSerializable objects.
     
  19. Offline

    Deleted user

    Okay and where is some documentation on the Configuration API so I may learn it?
     
  20. Offline

    Sagacious_Zed Bukkit Docs

    The same place as all the other official documentaion. The Wiki and The Javadoc
     
  21. Offline

    Deleted user

    Isn't the coniguration API like for a config ha? I mean it's not for saving data is it?
     
  22. Offline

    Sagacious_Zed Bukkit Docs

    I also call my fish, 'egg tart'. But that does not mean I can eat it like one.

     
  23. Offline

    TGF

    Weird;/
    my code (open)

    Code:
    package me.shaquu;
     
    import org.bukkit.ChatColor;
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.block.Block;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.World;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.BlockPlaceEvent;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    import me.shaquu.SerializableLocation;
    import java.io.*;
    import java.util.logging.Logger;
    import java.io.PrintWriter;
     
    public class TerrainS  extends JavaPlugin {
       
        public void onEnable(){;
            final Logger logger = getLogger();
            logger.info("-----TerrainS Activated!!!-----");
            FileConfiguration config = getConfig();
            config.addDefault("Path.subpath", "String");
            config.options().copyDefaults(true);
            saveConfig();
        }
     
        @EventHandler
        public void onBlockClick(BlockPlaceEvent event) {
            Player player = event.getPlayer();
            Block block = event.getBlockPlaced();
            int data = block.getTypeId();
            Location location = block.getLocation();
            int x = block.getX();
            int y = block.getY();
            int z = block.getZ();
       
            File dane = new File(getDataFolder(), "config.yml");
            String l = (new SerializableLocation(location)).toString();
            FileConfiguration config = getConfig();
            config.addDefault("Example.config","Happy?");
            config.options().copyDefaults(true);
            saveConfig();
           
         
            public static <T extends Object> void save(T obj, String path) throws Exception {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            }
           
            public static <T extends Object> T load(String path) throws Exception {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
            @SuppressWarnings("unchecked")
            T result = (T) ois.readObject();
            ois.close();
            return result;
            }
           
            public static void saveData() {
            File f = new File(CCMain.getInstance().getDataFolder(), "data.bin");
           
            try {
            if (!f.exists()) {
            CCMain.getInstance().getDataFolder().mkdirs();
            f.createNewFile();
            }
            save(x, "plugins/TerrainS/data.bin");
            save(y, "plugins/TerrainS/data.bin");
            save(z, "plugins/TerrainS/data.bin");
            save(data, "plugins/TerrainS/data.bin");
            } catch (Exception e) {
            e.printStackTrace();
            }
            }
           
            public static void loadData() {
            File f = new File(CCMain.getInstance().getDataFolder(), "data.bin");
           
            try {
            if (!f.exists()) {
            return;
            }
            save(x, "plugins/TerrainS/data.bin");
            save(y, "plugins/TerrainS/data.bin");
            save(z, "plugins/TerrainS/data.bin");
            save(data, "plugins/TerrainS/data.bin");
            } catch (Exception e) {
            e.printStackTrace();
            }
            }
       
           
           
     
       
            try{
                FileWriter fstream = new FileWriter("config.yml");
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(x+" "+y+" "+z+" "+data);
                out.close();
              }catch (Exception e){
                System.err.println("Error: " + e.getMessage());
              }
        }
    }
     
    


    Now it's little messy:p
    What I want to do?
    Get a location(x,y,z) and type of placed block and save it to the file.
    And save every block data(like upper) in the next line.
    Help... I'm working on it very long time and I'm terrified;(
     
  24. Offline

    Deleted user

    So how would I use the Configuration API to save to another file?
     
  25. Offline

    Sagacious_Zed Bukkit Docs

    If you mean another yaml file, then keep reading the wiki page.

    TGF
    Here is a sample plugin that saves the information for a location in a separate yaml file.
    https://github.com/SagaciousZed/SampleHome
     
  26. Offline

    Deleted user

    and what if I mean another file type like a binary file?
     
  27. Offline

    Sagacious_Zed Bukkit Docs

    Then you must implement FileConfiguration yourself. Much like how YamlConfiguration implements FileConfiguration.
     
  28. Offline

    TGF

    I
    It look very simple:p Thanks!
    I will change it to my situation later^^
     
  29. Offline

    Deleted user

    Well FFS could you possibly give me a little push and help me out with some code.. anything at all?
     
  30. Offline

    Sagacious_Zed Bukkit Docs

    Here is something
    Code:
     public class BinaryConfiguration extends FileConfiguration {
       ...
    }
     
Thread Status:
Not open for further replies.

Share This Page