Creating (and Writing to) a Text file.

Discussion in 'Plugin Development' started by FlareLine, Apr 28, 2013.

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

    FlareLine

    Hi all,
    I was wondering, what is the easiest way to create a blank text document in a specified path (e.g. the folder that a Plugin creates).
    In the onEnable method, I have my Plugin create a directory for itself, and I want to be able to create a text file in there, and then when a command is executed, it writes a number of lines about a specified player.

    E.g.
    The command "/store FlareLine 3" would store 3 lines of text in the text file, indicating the name "FlareLine"

    Any help would be appreciated. :)
     
  2. YOu can get your Plugin folder with "(YourPluginMainClass).getDataFolder()" and to write / read Files you can use a FileWriter / FileReader. In your case it sound like the BufferedReaer / BufferedWriter is the best for you.
    Just use google to learn how to use this Readers and Writers.

    Hope I could help,

    Oneric
     
  3. Offline

    FlareLine

    You may need to be a little more specific about this :p
    Code:
    //
    //            DON'T FORGET TO EDIT THE PLUGIN.YML TO THE CURRENT BUILD!!!!!!!!!
    //
     
    package user.flareline.logstore;
     
    import java.io.*;
     
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class LogStore extends JavaPlugin {
     
        public void onEnable() {
            getCommand("store").setExecutor(this);
            File dir = new File("plugins/LogStore");
            if (dir.exists()){
                getLogger().info("LogStore folder already exists!");
            }
            else {
                dir.mkdir(); 
                getLogger().info("LogStore folder created!");
            }
        }
     
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if(cmd.getName().equalsIgnoreCase("store") && args.length == 0) {
                sender.sendMessage(ChatColor.DARK_RED + "=====" + ChatColor.YELLOW + "LogStore" + ChatColor.DARK_RED + "=====");
                sender.sendMessage(ChatColor.GOLD + "/store" + ChatColor.DARK_GRAY + " - " + ChatColor.DARK_GREEN+ "Display this message.");
                sender.sendMessage(ChatColor.GOLD + "/store <name>" + ChatColor.DARK_GRAY + " - " + ChatColor.DARK_GREEN+ "Store an entry for 'name'.");
                sender.sendMessage(ChatColor.GOLD + "/store <name> <#>" + ChatColor.DARK_GRAY + " - " + ChatColor.DARK_GREEN+ "Store # entries for 'name'.");
                return true;
            }
            if(args.length == 1) {
                sender.sendMessage(ChatColor.AQUA + "Adding an entry under the name: " + ChatColor.DARK_AQUA + args[0]);
             
                try{
                    File logger = new File("/plugins/LogStore/logger.txt");
                    if (!logger.exists()){
                        logger.createNewFile();
                    }
                    FileWriter fw = new FileWriter(logger.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(args[0]);
                    bw.close();
                    sender.sendMessage("Entry Added!");
                } catch(IOException e) {
                    sender.sendMessage("Entry could not be added!");
                }
             
            }
            if(args.length == 2) {
                sender.sendMessage(ChatColor.AQUA + "Adding " + ChatColor.DARK_AQUA + args[1] + ChatColor.AQUA + " entries under the name: " + ChatColor.DARK_AQUA + args[0]);
     
                try{
                    File logger = new File("/plugins/LogStore/logger.txt");
                    if (!logger.exists()){
                        logger.createNewFile();
                    }
                    FileWriter fw = new FileWriter(logger.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(args[0]);
                    float entry = (Float.valueOf(args[1])).floatValue();
                 
                        int counter;
                        counter = 2;
                        while (counter != entry){
                            counter++;
                            bw.write(args[0]);
                    }
                    bw.close();
                } catch(IOException e) {
                    sender.sendMessage("Entry could not be added!");
                }
            }
            return false;
         
        }
     
        public void onDisable() {
     
            getLogger().info("onDisable has been invoked!");
        }
    }
    With this, I have already specified my directory I want it in, but I cannot create the file to write to it.
    That point being made, Does the BW/FW take into account that there may be lines of text already in the file, and go to the first blank line and write to that, rather than overwriting the contents of logger.txt?
     
  4. Offline

    skore87

    There is an overload for the FileWriter constructor where you can put a boolean to append to the file.
     
  5. Offline

    FlareLine

    skore87 Meaning the file is not being Loaded, or writing to the file is invalid?


    What the /store command is meant to do:
    • Show the Menu if no arguments have been presented.
    • e.g.(/store)
    • Display "Adding an entry for the name: FlareLine" when 1 argument has been presented.
    • e.g.(/store FlareLine)
      • Write a line in the logger.txt displaying "FlareLine".
    • Display "Adding # entries for the name: FlareLine" when 2 arguments have been presented.
    • e.g.(/store FlareLine 2)
      • Write 2 lines in the logger.txt not overwriting the previous entries displaying "FlareLine".
     
  6. Offline

    skore87

  7. Offline

    FlareLine

    skore87 No sorry... I will read that doc you referenced. :)
    I'm new to development, and have never gone about creating a file in Java.
    Just with my code, am I going about the right way with want I want to achieve or is there a better way?

    skore87 If anyone has an easy way of creating a file and writing text to it, and would be happy to share that piece of code with me, I'd be glad to rearrange it to suit my plugin.

    I recoded the Command method, and it is able to create a file in "c:\\logger.txt" which means that it is not obtaining the correct path to create the file in.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 1, 2016
  8. Offline

    skore87

    Just a simple google search will yield the results you're after. Should be within the first few results. But the constructor you want is FileWriter(File,Boolean) or FileWriter(String,Boolean) where the boolean is 'true'.
     
  9. Offline

    FlareLine

    But as the file can be written to C:\\, the problem is getting the correct directory to write the file to.

    It may have nothing to do with whether I am using a FileWriter or not, as using one does not solve the problem :O

    skore87 There has to be some way of doing it the way I am as the file can be written to a different directory.

    I have created the file in the /plugins/LogStore/ directory!!! :)
    Even though there may be unnecessary code in this method, it does create the directory so I'm keeping it like that until I release the first Build. Now to just edit the file.

    A quick question skore87 if I was to write to the logger.txt using FileWriter(logger, true) with an append function, does the append make the FW take into account the current contents of the file, or overwrite the contents of the file, whether or not the file had previous strings or not.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 1, 2016
  10. Offline

    zack6849

    that's what append means, it appends to the pre-existing text of the file.
     
  11. Offline

    FlareLine

    zack6849 I knew that.. <_>:p

    First release is out!!! :D (Beta LOL)
     
  12. Offline

    BajanAmerican

    This is my code:

    Code:java
    1. public static List<String> vips = new ArrayList<String>();
    2.  
    3. @Override
    4. public void onEnable() {
    5. vips.clear();
    6. if (!new File("C:/Users/Kyle/Desktop/D;KLGJASDFGJAKLDSFADFMGCBVDAMCBKJVADKL;GJFLKGJBLKSDZjnCFM/vips.txt").exists()) {
    7. try {
    8. new File(getDataFolder(), "C:/Users/Kyle/Desktop/D;KLGJASDFGJAKLDSFADFMGCBVDAMCBKJVADKL;GJFLKGJBLKSDZjnCFM/vips.txt").createNewFile();
    9. } catch (Exception e) {
    10. e.printStackTrace();
    11. }
    12. }
    13. try{
    14. FileReader file = new FileReader("C:/Users/Kyle/Desktop/D;KLGJASDFGJAKLDSFADFMGCBVDAMCBKJVADKL;GJFLKGJBLKSDZjnCFM/vips.txt");
    15. try {
    16. String line = br.readLine();
    17.  
    18. while (line != null) {
    19. line = br.readLine();
    20. vips.add(line);
    21. }
    22. } finally {
    23. br.close();
    24. }
    25. }
    26. catch (Exception e) {
    27. this.logger.info("WAS NOT ABLE TO READ FROM VIPS.TXT!!!");
    28. }

    FlareLine
     
  13. Offline

    FlareLine

    BajanAmerican Apparently it's bad to read from Hardcoded directories, and instead you should link it to a certain
    Code:
    getDataFolder().getPath();
    or something like that.
     
  14. Offline

    BajanAmerican

    I never got any error or lag when doing so, so I guess it works fine :p
    FlareLine
     
  15. Offline

    FlareLine

    BajanAmerican I realise it does not cause any issues with the Plugin, but when distributing it, you may find that the directory does not work. :D
     
Thread Status:
Not open for further replies.

Share This Page