SunnY
SunnY

Reputation: 59

Does not write text file from text input

I have written a code for "writing the content of textfield into a textfile". It has no error but it doesnt write anything in the text file ! Can anybody please help me and tell about my mistake ? or edit the code and put the whole code again.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    jButton1.addActionListener(new ActionListener(){
        public void actionPerformed(final ActionEvent e){
            handleActionPerformed(e);
        }
    });
}                                        

/**
* @param args the command line arguments
*/

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

//do you really need to pass ActionEvent in this case?
protected void handleActionPerformed(ActionEvent e) {
    BufferedWriter writer = null;
    try
    {
        String text = jTextField1.getText(); //get the text from the text field
        writer = new BufferedWriter(new FileWriter("D:\\Definition.txt"));
        writer.write(text); //write it in the file
        writer.flush(); //flush the write-buffer
    }
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }
    finally { //always close the stream in finally block
        try {
            if(writer != null)
                writer.close();
        }
        catch(IOException b) {
            b.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 198

Answers (1)

nullpotent
nullpotent

Reputation: 9260

handleActionPerformed(...) does nothing. This should work I believe...

jButton1.addActionListener(new ActionListener() {
  public void actionPerformed(final ActionEvent e) {
      handleActionPerformed(e);
  }                                     
}

//do you really need to pass ActionEvent in this case?
protected void handleActionPerformed(ActionEvent e) { 
 BufferedWriter writer = null;
 try
 {
   String text = jTextField1.getText(); //get the text from the text field
   writer = new BufferedWriter(new FileWriter("C:\\Definition.txt"));
   writer.write(text); //write it in the file
   writer.flush(); //flush the write-buffer
 }
 catch (IOException ioe)
 {
   ioe.printStackTrace();
 } 
 finally { //always close the stream in finally block
   try {
    if(writer != null) 
       writer.close();
   } catch(IOException e) {
     e.printStackTrace();
   } 
 }
}

Upvotes: 3

Related Questions