Need some help with writing/reading text files

Discussion in 'Plugin Development' started by tharvoil, Aug 21, 2011.

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

    tharvoil

    I'm working on a refer a friend style plugin, and I'm new to the programming scene so if it's a simple fix ignore me. I'm having issues trying to make it so when you issue a command /referredby <name>, it first checks a file to see if you have used the command before, if so then it stops the second part of the method, which is adding to a different file the total number of referrals you have.

    File setup for the users.txt should be:
    <name1>
    <name2>
    ect.

    File setup for referrals.txt should be:
    <name1> <total referrals(Int)> <Claimed referrals(Int)>
    <name2><total referrals(Int)> <Claimed referrals(Int)>
    ect.


    EDIT: Ignore my messy commentation, haven't bothered cleaning it up yet
    Here's my source:

    Main Class File:
    Code:
    package me.tharvoil.referafriend;
    
    import java.util.logging.Logger;
    import java.io.File;
    
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.util.config.Configuration;
    
    public class ReferAFriend extends JavaPlugin{
    
        public Configuration config;
    
        Logger log = Logger.getLogger("Minecraft");
        public Integer configItemID;
        public Integer configItemAmount;
            @Override
        public void onEnable(){
    
            if(!new File("plugins/ReferAFriend").exists()){
                new File("plugins/ReferAFriend").mkdir();
            }
            config = getConfiguration();
    
            configItemID = config.getInt("Reward Item ID", 264);
            configItemAmount = config.getInt("Amount to Award", 1);
            log.info("Refer a Friend v0.1 by tharvoil enabled.");
    
        }
    
        public void onDisable(){
            log.info("Refer a Friend disabled.");
        }
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            String referedBy;
            if(args[0] != null){
            referedBy = args[0];
            }else referedBy = null;
            Player refered = (Player) sender;
            if(cmd.getName().equalsIgnoreCase("referredby") || cmd.getName().equalsIgnoreCase("rfb")){ // If the player typed /refer then do the following...
                if (args.length != 1){
                    sender.sendMessage("Can only refer one person at a time.");
                }else{
    
                Info.referredCheck(refered, referedBy); //checks to see if the person who used the command has used it before, adds to file if they havent
                     // adds to the file that they have used the command
                // adds to the total referral amount of the argument
    
                }return true;
    
            }
            if(cmd.getName().equalsIgnoreCase("refercheck")){ // If the player typed /refer then do the following...
                Checks.checkReferals(refered); //checks total vs claimed referrals and awards items, then changes total
                return true;
            }
            return false;
        }
    }
    
    Info.java:
    Code:
    package me.tharvoil.referafriend;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    
    import org.bukkit.entity.Player;
    
    public class Info {
        public static void referredCheck(Player player, String referredBy){
            String name = player.getName();
            Boolean test = false;
            File f = new File("plugins/ReferAFriend/users.txt");
            try{
                if(!f.exists()){
                    f.createNewFile();
                }
                BufferedReader br = new BufferedReader(new FileReader(f));
    
                String[] save = new String[1024];
                String s = "";
                int j = 0;
    
                while((s = br.readLine()) != null){
                    test = true;
                    if(!s.split(" ")[0].equalsIgnoreCase(name)){
                        test = false;
                        save[j] = s;
                        j++;
                    }
                }
                br.close();
    
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    
                bw.write(name);
                bw.newLine();
    
                j = 0;
    
                while(save[j] != null){
                    bw.write(save[j]);
                    bw.newLine();
                    j++;
                }
    
                bw.flush();
                bw.close();
            }catch(Exception ex){
                System.out.println(ex);
            }//ends part one of file check(seeing if they've used before
            if(test != true){
                player.sendMessage("You have already been referred.");
            }else{
                f = new File("plugins/ReferAFriend/referrals.txt");
                try{
                    if(!f.exists()){
                        f.createNewFile();
                    }
                    BufferedReader br = new BufferedReader(new FileReader(f));
    
                    String[] save = new String[1024];
                    String s = "";
                    int j = 0;
    
                    while((s = br.readLine()) != null){
                        if(!s.split(" ")[0].equalsIgnoreCase(referredBy)){
                            save[j] = s;
                            j++;
                        }
                    }
                    br.close(); //should put the reader @ the users name
                    String t = s;
                    @SuppressWarnings("null")
                    int total = Integer.parseInt(t.split(" ")[1]);
                    int claimed = Integer.parseInt(t.split(" ")[2]);
    
                    BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    
                    bw.write(referredBy + total + claimed);
                    bw.newLine();
    
                    j = 0;
    
                    while(save[j] != null){
                        bw.write(save[j]);
                        bw.newLine();
                        j++;
                    }
    
                    bw.flush();
                    bw.close();
    
                }catch(Exception e){
                    System.out.println(e);
                }
            }
    
        }
    
    }
    
     
  2. Offline

    ItsHarry

    It would be easier to use a hashmap instead of a text file:

    HashMap map<Player, boolean> = new HashMap<Player, boolean>();
    if (map.has(player)) { //return true or false since the hashmap is <Player, boolean>
    doblah();
    }

    And you can add players to the hashmap by doing:

    map.put(player, true);
     
  3. Offline

    tharvoil

    I've never done anything with hashmaps before, I looked at the tutorial on the "Huge Plugin Tutorial", but that seemed to confusing for me to figure out, can you point me towards a better one?

    Also I do kind of understand that one, once they are in the hashmap then it works like my first txt fiel where it checks to see if they have used the command before.

    Do hashmaps save through the server going down is the main question however? If so then this would work perfectly, prehaps for both files.

    Thanks for the help!
     
  4. Offline

    ItsHarry

    ^ The information in a HashMap will not be lost until the server is restarted, or the server is reloaded (/reload).

    However, it's also possible to save hashmaps to files.

    And sorry, I don't know of any good HashMap tutorials, you'll have to find some yourself using Google
     
  5. Offline

    ParkourGrip

    its easy...
    Hashmap is like a database. You have a key and a valute. For every key there is a valute.

    You create a new hashmap like this:
    HashMap hashmapname<variable type 1 (key), variable type 2 (valute)>= new HashMap<variable type 1 (key), variable type 2 (valute)>();

    you add stuff in it like this:
    hashmapname.put(key, valute);

    And you get valute from key like this:
    hashmapname.get(key);

    Its like adding and getting stuff from a database. But it dose not have to be a text or a number... It can be eney variable like Player, Entity, Creature... You chose them while creating the hashmap.
     
  6. Offline

    tharvoil

    So I think I get it - I can set one up as <playername (player), referedby (player), refered (int), claimed (int)>, that one hashmap should store everything I need?
     
  7. Offline

    SpikeMeister

    Knowing hashmaps is good, but I recommnend you use a Properties object. It is backed by a hashmap and lets you save to disk. Look here for docs on how to use it (I think it's also mentioned in the tutorial).

    A hashmap/properties object probably won't work with the structure you said for the configs in your OP but if you rework the way you want to store the data it can make your life easier.

    You will probably want to have the key as the Player, and the value will be the data which refers to them (stored in a string or perhaps another data structure).

    Another option is to have a new entry for every different type of data for each player - for instance you might have a key "Player.RefferedBy" and the value will be the player who referred them. This will be much easier to implement and work with and is a perfectly acceptable solution, though possibly less tidy.
     
Thread Status:
Not open for further replies.

Share This Page