2 Replies Latest reply: Mar 21, 2007 9:37 AM by 807606 RSS

    error with BufferedWriter

    807606
      I have an error in my code trying to write to a file.
      It creates the directory and file if necessary, but the file is empty, nothing is written to it.
      Can someone spot the problem?
      Thanks!
      public void writeOutputFile2 (File file)
      {
        // create directory if necessary
        File directory = new File (file.getParent());  
        if ( ! directory.isDirectory() )
        {
          directory.mkdirs();
        }
        
        File newfile = new File(file.toString()); // create file
            
        try
        {
          // Create file if it does not exist
          boolean success = newfile.createNewFile();
        }
        catch (IOException e1)
        {
          System.out.println("error creating file to write to: " + newfile.toString());
          e1.printStackTrace();
        }
           
        FileWriter fileWriter = null;
      
        try
        {
          fileWriter = new FileWriter (newfile, true); // true == append
        }
        catch (FileNotFoundException e)
        {
          System.out.println (newfile.toString() + " not found\n");
          e.printStackTrace();
        }
        catch (IOException e)
        {
          System.out.println (newfile.toString() + " not found\n");
          e.printStackTrace();
        }
           
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        
        try
        {
          bufferedWriter.write("hello\n");
          fileWriter.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        } 
      }