Java - Please look at this code and tell me what's wrong with it

Discussion in 'Java' started by Brentatechnologies, Aug 30, 2011.

  1. Brentatechnologies

    Brentatechnologies New Member

    Joined:
    Aug 22, 2011
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Hey All,

    I recently as said in my introduction became interested in coding my own RSPS, I'm using Project Insanity Source code and Client, and I was adding in a command for a ::trusted, which builds a list of trusted players....

    This is the code im using but I'm thinking that it's wrong somehow, can someone please read over it and add suggestions :)

    Code:
    /**
     * Writes the username into a text file - use ::trusted username
     **/
     public static void addUsernameToFile(String Name) {
      try {
       BufferedWriter out = new BufferedWriter(new FileWriter("./Data/trusted/TrustedPlayers.txt", true));
      try {
        out.newLine();
        out.Write(Name);
       } finally {
        out.close();
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
     
    Last edited by a moderator: Aug 30, 2011
  2. ManzZup

    ManzZup New Member

    Joined:
    May 9, 2009
    Messages:
    278
    Likes Received:
    43
    Trophy Points:
    0
    Occupation:
    Production Manager:Software @ ZONTEK
    Location:
    Sri Lanka
    Home Page:
    http://zontek.zzl.org
    herez the corrected version of code with some addition, more suitable error handling and example of implementing

    Code:
    import java.io.*; 
    class Test{
    static BufferedWriter out = null;
    	public static void main(String... args){
    		try{
    		addUsernameToFile("ManZzup");
    		}catch(Exception e){
    			e.printStackTrace();
    		}finally{
    			try{
    				out.close();
    			}catch(Exception e){}
    		}
    	}
    
    public static void addUsernameToFile(String Name) throws IOException {
      out = new BufferedWriter(new FileWriter("TrustedPlayers.txt", true));
      out.newLine();
      out.write(Name);
     }
    
     }
    
    as for the errors, there were several,
    you had a try block opened but never closed, i guess you havent put the bottom part of the code
    you havent caught the BufferedWriter.close() throwing exceptio in the finally block
    it is always good to have finally after all
    and the best pratice would be to simply throw the error out of the method body and handle them all at one place
    and BufferedReader.write method has a simple 'w'

    hope this code will help :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice