Writing to a text file using Java

Below is an example of writing to the text file using FileWriter class

Note that we have added FileWriter locfile = null; before the try block because we are using locfile in finally block other wise locfile would be just local to try block and won't be accessible in finally block

FileWriter locfile = null;
      try {
          locfile = new FileWriter("locations.txt");
          //Here locations is ahashap that cotains keys as Strings and values as objects of user defined class location  
           for (location location : locations.values()) {
          //write location id and description to file for the location objects in locations map
          locfile.write(location.getLocationId() + ":" + location.getDescription() + "\n");
          }
      }
       catch (IOException e) {
         e.printStackTrace();
      }

     finally{
          System.out.println("In the finally block");
        Please note that its very imp. to close the filewrite object in the finally block to while writing code to a text file as and also note that close itself can 
       cause exception so we have to put close in another
          try catch block in finally block
          try {
              if(locfile!=null){
              locfile.close();}
          } catch (IOException e) {
              e.printStackTrace();
          }
      }