Search code examples
javamenufilewriterbufferedwriterwriter

write() method not recognizing TextArea


I've written an ActionListener for a toolbar menu item which is called "Save", on click I want the program to save the content of TextArea l1 into a .txt file called "filename", so this si the code that I've come up with (since the program is really long, I've pasted here only the code fragments where the error is located or might be located):

import java.awt.*;
import java.awt.event.*;

...

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;

class Progetto extends Frame {
...

  private TextArea l1 = new TextArea();
  ...

  private MenuBar menubar;
  private Menu file;
  private MenuItem save;

  ...

  salva.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt"));
          l1.write(fileOut);
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
    });

When I run this program I get the following error:

Error: cannot find symbol
symbol:   method write(java.io.BufferedWriter)
location: variable l1 of type java.awt.TextArea

I've looked everywhere in the documentation and forums, but I can't understand why this error occurs neither how to solve it...

What can I do to fix this error?

EDIT
The TextArea looks like this:

Jack: 9.0
Mark: 9.0
Nick: 1.0
Linn: 6.5
Jhon: 3.5

Solution

  • Change your code inside action listener to :

    salva.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            try {
              String text = l1.getText();
              if ( text != null  && !text.isEmpty() )
              {
                 String[] lines = text.split("\n");
                 BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt"));
                 for ( String line : lines )
                 {
    
                    fileOut.write( line, 0, line.length()-1 );
                    fileOut.newLine();
                 }
    
                 fileOut.close();
              }
    
    
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });