Loading text file, problem

Discussion in 'Plugin Development' started by kmccmk9, Aug 23, 2011.

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

    kmccmk9

    Hello, I'm trying to load lines from a text file. However no matter what I do the length of my array is 0. Therefore I believe it is not loading for the file. Why? Thanks for any help!

    Code:java
    1.  
    2. package com.kmccmk9.HelpMeAdvanced;
    3.  
    4. // All the imports
    5. import java.io.BufferedWriter;
    6. import java.io.File;
    7. import java.io.FileInputStream;
    8. import java.io.FileOutputStream;
    9. import java.io.FileWriter;
    10. import java.io.IOException;
    11. import java.io.Writer;
    12. import java.util.ArrayList;
    13. import java.util.Properties;
    14. import java.util.Scanner;
    15.  
    16. import org.bukkit.ChatColor;
    17. import org.bukkit.command.Command;
    18. import org.bukkit.command.CommandSender;
    19. import org.bukkit.entity.Player;
    20. import org.bukkit.plugin.PluginDescriptionFile;
    21. import org.bukkit.plugin.java.JavaPlugin;
    22.  
    23. import com.nijiko.permissions.PermissionHandler;
    24. import com.nijikokun.bukkit.Permissions.Permissions;
    25.  
    26. import org.bukkit.plugin.Plugin;
    27. import org.bukkit.Server;
    28.  
    29. /**
    30.  * HelpMeAdvanced for Bukkit
    31.  *
    32.  * @author kmccmk9
    33.  */
    34.  
    35. //Starts the class
    36. public class HelpMeAdvanced extends JavaPlugin{
    37. Server server;
    38. String variable;
    39. Scanner msgs;
    40. ArrayList<String> messagestoprint = new ArrayList<String>();
    41. int arraylength;
    42. public static PermissionHandler permissionHandler;
    43. //Define File Variables
    44. static String mainDirectory = "plugins/HelpMeAdvanced"; //sets the main directory for easy reference
    45. static File messages = new File(mainDirectory + File.separator + "messages.txt"); //the file separator is the / sign, this will create a new Zones.dat files in the mainDirectory variable listed above, if no Zones directory exists then it will automatically be made along with the file.
    46. // onDisable
    47. public void onDisable() {
    48. PluginDescriptionFile pdfFile = this.getDescription();
    49. System.out.println( pdfFile.getName() + " is disabled!" );
    50. }
    51. // onEnable
    52. public void onEnable() {
    53. server = this.getServer();
    54. PluginDescriptionFile pdfFile = this.getDescription();
    55. System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
    56. setupPermissions();
    57. //Setup Files
    58. new File(mainDirectory).mkdir(); //makes the Zones directory/folder in the plugins directory
    59. if(!messages.exists()){ //Checks to see if the zones file exists, defined above, if it doesn't exist then it will do the following. the&nbsp;! turns the whole statement around, checking that the file doesn't exist instead of if it exists.
    60. try { //try catch clause explained below in tutorial
    61. messages.createNewFile(); //creates the file zones.dat
    62. FileWriter writer = new FileWriter(messages,true);
    63. BufferedWriter out = new BufferedWriter(writer);
    64. out.write("An Admin or SuperAdmin will come and help you soon as possible.");
    65. out.newLine();
    66. out.write("If no one come and helps you within 5 minutes, perform the command again.");
    67. out.newLine();
    68. out.write("Message sent to Admins");
    69. out.close();
    70. } catch (IOException ex) {
    71. ex.printStackTrace(); //explained below.
    72. }
    73.  
    74. } else {
    75.  
    76. openFile();
    77. readFile();
    78. closeFile();
    79.  
    80. }
    81. }
    82.  
    83. private void openFile() {
    84. try{
    85. msgs = new Scanner(new File("messages"));
    86. }catch (Exception ex){
    87. System.out.println("[HelpMeAdvanced] Could not find messages.txt, did you delete it?");
    88. }
    89. }
    90.  
    91. private void readFile() {
    92. if (!msgs.hasNextLine()){ //Check if there are no lines at all
    93. server.broadcastMessage("[RandomAnnounce] Messages.txt is empty.");
    94. }else{
    95. messagestoprint.clear(); //Clear the ArrayList (For using the reload command)
    96. while (msgs.hasNextLine()){
    97. String messagetofile = msgs.nextLine(); //Set the next line to a string
    98. messagetofile = messagetofile.replaceAll("(&([a-f0-9]))", "\u00A7$2"); //Replace colour codes
    99. messagestoprint.add(messagetofile); //Add to the ArrayList
    100. }
    101. }
    102. }
    103.  
    104. private void closeFile() {
    105. msgs.close();
    106. }
    107.  
    108. private void setupPermissions() {
    109. Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions");
    110.  
    111. if (this.permissionHandler == null) {
    112. if (permissionsPlugin != null) {
    113. this.permissionHandler = ((Permissions) permissionsPlugin).getHandler();
    114. } else {
    115. System.out.println("Permission system not detected, defaulting to OP");
    116. }
    117. }
    118. }
    119. // Command system
    120. public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
    121. Player[] players;
    122. int total;
    123. if (sender instanceof Player) {
    124. Player player = (Player) sender;
    125. if(commandLabel.equalsIgnoreCase("helpme")) {
    126. if (args.length == 1)
    127. {
    128. variable = args[0];
    129. if (variable.equalsIgnoreCase("help"))
    130. {
    131. player.sendMessage("Typing in /helpme will alert Admins that you need help!");
    132. }
    133. if (!variable.equalsIgnoreCase("help"))
    134. {
    135. player.sendMessage(ChatColor.DARK_RED + "Unrecognized argument. Typing in /helpme will alert Admins that you need help!");
    136. }
    137. }
    138. else if (args.length == 0)
    139. {
    140. arraylength = messagestoprint.size();
    141. player.sendMessage("test");
    142. player.sendMessage(Integer.toString(arraylength));
    143. players = server.getOnlinePlayers();
    144. total = players.length;
    145. int i = 0;
    146. while (i < total)
    147. {
    148. if (HelpMeAdvanced.permissionHandler.has(players[I], "helpmeadvanced.admin") || players[I].isOp() || players[I].hasPermission("helpmeadvanced.admin")) {[/I][/I][/I]
    149. [I] players[I].sendMessage(ChatColor.DARK_RED + player.getDisplayName() + ChatColor.DARK_GREEN + " needs some help!" + " (" + player.getLocation().getWorld() + player.getLocation().getBlockX() + ',' + player.getLocation().getBlockY() + ',' + player.getLocation().getBlockZ() + ")"); [/I][/I]
    150. [I] }[/I]
    151. [I] i++;[/I]
    152. [I] } [/I]
    153. [I] }[/I]
    154. [I] }[/I]
    155. [I] }[/I]
    156. [I] return true;[/I]
    157. [I] }[/I]
    158. [I]}[/I]
    159. [I][/I]
     
  2. Offline

    Tahkeh

    I'm not quite sure what you're doing here because I've never used the Scanner class... :p But my plugin used to have this really simple method for getting each line of a .txt file and formatting it into a String array.

    Code:
    public String[] read() {
        ArrayList lines = new ArrayList();
        try
        {
          BufferedReader in = new BufferedReader(new FileReader("path/goes/here.txt"));
          String str;
          while ((str = in.readLine()) != null)
          {
            String str;
            lines.add(str);
          }
          in.close();
        } catch (IOException localIOException) {
        }
        return (String[])lines.toArray(new String[0]);
      }
     
    kmccmk9 likes this.
  3. Offline

    kmccmk9

    Ah ok I see what you did there. Ya the reader class supposedly goes through all the lines in a file for you.
     
  4. Offline

    Tahkeh

    Right. And then when the line ends, it adds that line to the array and keeps going until it's finished. It sounds like what you needed, correct?
     
  5. Offline

    kmccmk9

    Yup. I'm just trying to really understand how to use the scanner though. It seems to be the most common in many plugins that I have looked through the source of.
     
  6. Offline

    badbh222

    One thing I can see, is if you run the plugin without the messages file, it will create the file, but won't open, read and close it, only when you run it while the file is there. Other than that, it should work, from what I can tell... :confused:
     
  7. Offline

    kmccmk9

    Really? Ya I noticed and tested that it will create the file. But why won't it load them into the array? Every time I check it says it has a size of 0.
     
  8. Offline

    badbh222

    Aha!

    Code:
    msgs = new Scanner(new File("messages"));
    Should be:

    Code:
    msgs = new Scanner(new File(messages));
     
    kmccmk9 likes this.
  9. Offline

    kmccmk9

    Alright! Nice catch! I guess sometimes it takes a second pair of eyes to see an error. I will give it a shot when my server is up today.
     
  10. Offline

    badbh222

    And yeah, you should get rid of the "else" in "onEnable", so it always reads the file, not just when it already exists. :)
     
    kmccmk9 likes this.
  11. Offline

    kmccmk9

    Alright I will do that!
     
  12. Offline

    badbh222

    Certainly does... :)
     
  13. Offline

    kmccmk9

    Well that gave me an error. It wants me to change messages to the type String instead of File. What should I do?
     
  14. Offline

    badbh222

    Oh, of course, try this instead of "messages".

    Code:
    mainDirectory + File.separator + "messages.txt"
     
    kmccmk9 likes this.
  15. Offline

    kmccmk9

    Even though my variable messagesalready has that?
     
  16. Offline

    badbh222

    Oh right, you should be able to just do this:

    Code:
    msgs = new Scanner(messages);
    Sorry, it's early morning, and not much sleep. :D
     
    kmccmk9 likes this.
Thread Status:
Not open for further replies.

Share This Page