Writing to new line in txt file

Discussion in 'Plugin Development' started by ChromeHD__, Oct 20, 2013.

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

    ChromeHD__

    Okay i have created a referral plugin and i make it save who you refered and who issued the command and it saves it fine on the first line but if you do the command again it just replaces it
     
  2. Offline

    Cr4zy[Box]

    It should work if u type this inside the string, for example: "I m boss \n And i love my self"
     
  3. Offline

    ChromeHD__

    Forgive the messy code but here it is i know there is some other stuff to be fixed but im just intrested in this problem right now
    Code:java
    1. package Main;
    2.  
    3.  
    4.  
    5. import java.io.BufferedWriter;
    6. import java.io.File;
    7. import java.io.FileWriter;
    8. import java.io.IOException;
    9.  
    10. import org.bukkit.Bukkit;
    11. import org.bukkit.ChatColor;
    12. import org.bukkit.Color;
    13. import org.bukkit.GameMode;
    14. import org.bukkit.Server;
    15. import org.bukkit.World;
    16. import org.bukkit.command.Command;
    17. import org.bukkit.command.CommandSender;
    18. import org.bukkit.entity.Player;
    19. import org.bukkit.plugin.java.JavaPlugin;
    20.  
    21. @SuppressWarnings("unused")
    22. public class refer extends JavaPlugin{
    23.  
    24. public void onEnable(){
    25. File refer = new File(getDataFolder() + File.separator + "Refer");
    26. File usernames = new File(getDataFolder() + File.separator + "Refer" + "Usernames.txt");
    27. if (!refer.exists()) {
    28. if (refer.mkdir()) {
    29. System.out.println("Directory is created!");
    30. try {
    31. refer.createNewFile();
    32. } catch (IOException e) {
    33. System.out.println("Failed to create directory!2");
    34. e.printStackTrace();
    35. }
    36. } else {
    37. System.out.println("Failed to create directory!");
    38. }
    39. }
    40. getLogger().info("Enabled!");
    41. }
    42.  
    43. public void onDisable(){
    44. getLogger().info("Disabled");
    45. }
    46.  
    47. @SuppressWarnings("deprecation")
    48. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
    49. File usernames = new File(getDataFolder() + File.separator + "Refer" + File.separator + "Usernames.txt");
    50. Player player = (Player) sender;
    51. Server server = player.getServer();
    52. Player target1 = Bukkit.getServer().getPlayer(args[0]);
    53. if(cmd.getName().equalsIgnoreCase("refer")){
    54. if (args.length == 1) {
    55.  
    56. if (player.getServer().getPlayer(args[0]) != null) {
    57. Player target = player.getServer().getPlayer(args[0]);
    58.  
    59. sender.sendMessage(ChatColor.GREEN+ "[Referal] "+ ChatColor.GOLD +" : "+ ChatColor.AQUA +"You just refered " + target.getDisplayName());
    60. target.sendMessage(ChatColor.GREEN+ "[Referal] "+ ChatColor.GOLD +" : "+ ChatColor.AQUA +"You have just been refered by " + player.getDisplayName());
    61.  
    62. try{
    63.  
    64.  
    65.  
    66. FileWriter fw = new FileWriter(usernames.getAbsoluteFile());
    67. bw.write("Refered " + args[0] + " : " + "Command sent by " + sender.getName());
    68. bw.newLine();
    69. bw.flush();
    70. bw.close();
    71. }catch(IOException e){
    72.  
    73. }
    74. }else{
    75. sender.sendMessage(ChatColor.RED+ "[Error] "+ ChatColor.GOLD +" : "+ChatColor.AQUA +"The member you tried to refer is not online");
    76. }
    77.  
    78. }
    79. }
    80.  
    81.  
    82.  
    83. return false;
    84. }
    85. }


    Bump*

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

    Cr4zy[Box]

    have you tried what i told ya?
     
  5. Offline

    ChromeHD__

    I tried that before and it didn't work

    So i dont know what to try now :L

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

    Briggybros

  7. Offline

    NathanWolf

  8. Offline

    zack6849

    BufferedWriters or any sort of filewriters have an option to either append, or overwrite the file, for a bufferedwriter, it'd look something like this.

    Code:
    BufferedWriter writer = new BufferedWriter(new FileWriter(usernames, true));
    
     
  9. Offline

    The_Doctor_123

    Holy bumparoo.....
    1. You need more patience.
    2. It is against the rules to bump before 24 hours before your last post.

    As for your issue, show us your new code.

    EDIT: Did you call flush() after writing to the PrintWriter?
     
  10. Offline

    ChromeHD__

    Yeah sorry I did call flush() but now nothing is getting sent to the txt file
     
  11. Offline

    PolarCraft

  12. Offline

    ChromeHD__

    The code is the same as the one I posted before because none of the above suggestions worked
     
  13. Offline

    The_Doctor_123

    ChromeHD__
    Okay.. here's what you're going to need to do. Define these at the top of your class:
    Code:java
    1. File usernames = new File(getDataFolder() + File.separator + "Refer" + File.separator + "Usernames.txt");
    2. PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(usernames, true)));

    Then to write a line to the file, just use:
    Code:
    pw.println(/*Whatever you want to print to file*/);
    pw.flush();
    Probably should close the PrintWriter too in the onDisable() method.
    Code:
    pw.close();
     
  14. Offline

    ChromeHD__

    That problem is fixed now thanks but there is one more little problem I need help with it writes to the txt file now how do I make it check if the user has already referred someone
     
  15. Offline

    NathanWolf

    You will need to read the file before appending to it if you want to check for duplicates before adding.

    Look at BufferedReader.readLine:

    http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

    Just follow the same basic pattern with Readers as you did with Writers to open the file. Then, call readLine() until you get null, adding each String you get back to a Set<String>.

    You can use .contains() to check that set to see if the new username is already there - if it is, do nothing. If it is not, add it to the set.

    At that point, you can either just invoke your current code and append to the file, or write the contents of the Set out to a file (which makes the issues with appending irrelevant, though it sounds like you've got that worked out).

    Also, just a general pointer- Google and Stack Overflow are great resources for general (non-Bukkit-specific) Java questions, too- a lot of the simpler stuff has usually been asked and answered already somewhere, so you don't have to wait for a response. It can be tricky to know what to search for in the first place, though.
     
  16. Offline

    ChromeHD__

    Thanks man I got it to work a while ago but for some reason it wouldn't let me use else after

    i tried using that but it wouldnt let me use a else statement
    Code:java
    1. BufferedReader br = null;
    2.  
    3. try {
    4.  
    5. String sCurrentLine;
    6.  
    7. br = new BufferedReader(new FileReader(usernames.getAbsolutePath()));
    8.  
    9. while ((sCurrentLine = br.readLine()) != null) {
    10. if(sCurrentLine.contains("Command sent by " + sender));
    11. sender.sendMessage(ChatColor.RED+ "[Error] "+ ChatColor.GOLD +" : "+ChatColor.AQUA +"You have already refered someone");
    12. }
    13.  
    14. } catch (IOException e) {
    15. } finally {
    16. try {
    17. if (br != null)br.close();
    18. } catch (IOException ex) {
    19. }
    20. }


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

    NathanWolf

    Looks like a stray semicolon on line 10 - I think you want something like

    Code:java
    1. BufferedReader br = null;
    2. boolean isDuplicate = false;
    3. try {
    4.  
    5. String sCurrentLine;
    6.  
    7. br = new BufferedReader(new FileReader(usernames.getAbsolutePath()));
    8.  
    9. while ((sCurrentLine = br.readLine()) != null) {
    10. if(sCurrentLine.contains("Command sent by " + sender)) {
    11. sender.sendMessage(ChatColor.RED+ "[Error] "+ ChatColor.GOLD +" : "+ChatColor.AQUA +"You have already refered someone");
    12. isDuplicate = true;
    13. }
    14. }
    15.  
    16. } catch (IOException e) {
    17. } finally {
    18. try {
    19. if (br != null)br.close();
    20. } catch (IOException ex) {
    21. }
    22. }
    23.  
    24. if (!isDuplicate) {
    25. // ... call code here to append to file
    26. }


    Note you probably don't want to try to write to the file while you have it open for reading, though I guess I don't know what the locking situation is so it might work.
     
  18. Offline

    ChromeHD__

  19. Offline

    NathanWolf

    The code you're using to write out the file hasn't changed, though? Can you re-test just that part in isolation?
     
  20. Offline

    ChromeHD__

    nothing changed and now it wont say anything ingame
     
  21. Offline

    NathanWolf

    Do you want to post your new code?
     
  22. Offline

    ChromeHD__

    Code:java
    1. package Main;
    2.  
    3.  
    4.  
    5. import java.io.BufferedReader;
    6. import java.io.BufferedWriter;
    7. import java.io.File;
    8. import java.io.FileReader;
    9. import java.io.FileWriter;
    10. import java.io.IOException;
    11.  
    12.  
    13. import java.io.LineNumberReader;
    14. import java.io.PrintWriter;
    15.  
    16. import org.bukkit.Bukkit;
    17. import org.bukkit.ChatColor;
    18. import org.bukkit.Color;
    19. import org.bukkit.GameMode;
    20. import org.bukkit.Server;
    21. import org.bukkit.World;
    22. import org.bukkit.command.Command;
    23. import org.bukkit.command.CommandSender;
    24. import org.bukkit.entity.Player;
    25. import org.bukkit.plugin.java.JavaPlugin;
    26.  
    27. @SuppressWarnings("unused")
    28. public class refer extends JavaPlugin{
    29. public static int currentLine = 0;
    30. public void onEnable(){
    31. File refer = new File(getDataFolder() + "");
    32. File usernames = new File(getDataFolder() + File.separator + "" + File.separator + "Usernames.txt");
    33.  
    34. if(!refer.exists()){
    35. refer.mkdir();
    36.  
    37. System.out.println("[Refer] Folder has been made");
    38. }else{
    39. System.out.println("[Refer] Loaded Usernames.txt");
    40. }
    41. if (!usernames.exists()) {
    42. try {
    43. usernames.createNewFile();
    44. } catch (IOException e) {
    45. e.printStackTrace();
    46. }
    47. }
    48.  
    49. getLogger().info("Enabled!");
    50. }
    51.  
    52.  
    53. public void onDisable(){
    54. getLogger().info("Disabled");
    55. }
    56.  
    57. @SuppressWarnings("null")
    58. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
    59. File usernames = new File(getDataFolder() + File.separator + "" + File.separator + "Usernames.txt");
    60. try {
    61. @SuppressWarnings("resource")
    62. PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(usernames, true)));
    63. } catch (IOException e1) {
    64. e1.printStackTrace();
    65. }
    66. Player player = (Player) sender;
    67. Server server = player.getServer();
    68. Player target1 = Bukkit.getServer().getPlayer(args[0]);
    69. if(cmd.getName().equalsIgnoreCase("refer")){
    70. if(args.length == 0){
    71. sender.sendMessage(ChatColor.RED+ "[Usuage] "+ ChatColor.GOLD +" : "+ChatColor.GREEN +"/refer <Username>");
    72. }else if (args.length == 1) {
    73. if (!(player.getServer().getPlayer(args[0]) != null)) {
    74. sender.sendMessage(ChatColor.RED+ "[Error] "+ ChatColor.GOLD +" : "+ChatColor.AQUA +"The member you tried to refer is not online");
    75. }else{
    76. Player target = player.getServer().getPlayer(args[0]);
    77.  
    78. BufferedReader br = null;
    79. boolean isDuplicate = false;
    80. try {
    81.  
    82. String sCurrentLine;
    83.  
    84. br = new BufferedReader(new FileReader(usernames.getAbsolutePath()));
    85.  
    86. while ((sCurrentLine = br.readLine()) != null) {
    87. isDuplicate = false;
    88. if(isDuplicate = false){
    89. try{
    90.  
    91. PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(usernames,true)));
    92. out.println("Refered " + target.getDisplayName() + " : " + "Command sent by " + sender.getName());
    93. out.close();
    94. }catch(IOException e){
    95.  
    96. }
    97. sender.sendMessage(ChatColor.GREEN+ "[Referal] "+ ChatColor.GOLD +" : "+ ChatColor.AQUA +"You just refered " + target.getDisplayName());
    98. target.sendMessage(ChatColor.GREEN+ "[Referal] "+ ChatColor.GOLD +" : "+ ChatColor.AQUA +"You have just been refered by " + player.getDisplayName());
    99.  
    100.  
    101. }
    102. }
    103. if(sCurrentLine.contains("Command sent by " + sender)) {
    104. sender.sendMessage(ChatColor.RED+ "[Error] "+ ChatColor.GOLD +" : "+ChatColor.AQUA +"You have already refered someone");
    105. }
    106.  
    107.  
    108. }catch (IOException e) {
    109. } finally {
    110. try {
    111. if (br != null)br.close();
    112. } catch (IOException ex) {
    113. }
    114.  
    115. }
    116. return false;
    117. }
    118. }
    119. }
    120. return false;
    121. }
    122. }
     
  23. Offline

    NathanWolf

    Make sure not to do that :)

    You need to first create the FileReader, read in the file, and decide whether you need to add it. Then close that reader before going on to the FileWriter. Just like the pseudocode I wrote.

    I'm not certain this is the problem, but I can imagine what you're doing up there is going to have issues.

    It might help to separate out some of this code into functions at this point to keep it organized - e.g. "void addToFile(String username)" and "boolean fileContains(String username)".

    Good luck!
     
Thread Status:
Not open for further replies.

Share This Page