Solved

Saving edited text to a file from a JTextArea

Posted on 2009-05-12
7
1,426 Views
Last Modified: 2013-11-23
I keep trying to compile the following code below however after i attempted to implement a way to save the modified text from the JTextArea i keep getting the following error during compile:

fileio.java:158: cannot find symbol
symbol  : constructor FileWriter(java.io.File)
location: class FileWriter
         FileWriter first = new FileWriter(new File("first.txt"));

I loaded:
import java.io.*;


So i am very confused as to why I am getting this error. Any help would be appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.*;
 
 
 
 
 
public class fileio
{
	String word;
	JTextArea wordDocModify;
	String openedDoc;
	public static void main (String[] args)throws Exception
	{
	fileio docEdit = new fileio();
	docEdit.textEditorInitialScreen();
//	docEdit.docEditor();
 
	}
 
public void textEditorInitialScreen() throws Exception
{
	
  	  JFrame jF1 = new JFrame("Text Editor"); // Set the window title.
 
      // Set the size of the JFrame to 1150 x 629 pixels. 
      jF1.setSize(1150, 629);
		
		
		JLayeredPane jP1 = new JLayeredPane();
		jP1.setLayout(null);
		
			
		JTextArea wordDocNew = new JTextArea(5, 10);
		wordDocNew.setLineWrap(true);
		
		
				JButton startOpen = new JButton("OPEN");
		           startOpen.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e)
						{
					//	textEditorEditingScreen();
					try {
    textEditorEditingScreen();
						} 
catch (IOException e1){
    e1.printStackTrace();
}
						}
            });
		
		JButton startSave = new JButton("SAVE");
  			         startSave.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) 
						{
						 System.exit(0);
						}
            });
 
		JButton startClose = new JButton("QUIT");
		           startClose.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) 
						{
						 System.exit(0);
						}
            });
				
	
		
      // Post the JLabels on the JPanel
	   // jPanel1.add(pictureJLabel); // Post the BSG start screen. 
		jP1.add(wordDocNew, JLayeredPane.PALETTE_LAYER);
		jP1.add(startClose, JLayeredPane.PALETTE_LAYER); 
		jP1.add(startOpen, JLayeredPane.PALETTE_LAYER);
		jP1.add(startSave, JLayeredPane.PALETTE_LAYER);
		
		wordDocNew.setBounds(10,20,900,500);
		startOpen.setBounds(970,50,100,20);
		startSave.setBounds(970,100,100,20);
		startClose.setBounds(970,200,100,20);
 
 
 
      // Post the JPanel into the JFrame
      jF1.getContentPane().add(jP1);
		
      // Displays the JFrame
      jF1.setVisible(true);
		
 
}
 
public void textEditorEditingScreen() throws IOException
{
 
	 //FileReader dataIn = new FileReader("text.txt");
	 String filename = File.separator + "tmp";
    JFileChooser fc = new JFileChooser(new File(filename));
    // Show open dialog
    fc.showOpenDialog(null);
    File f = fc.getSelectedFile();
 
    // Show save dialog
 //   fc.showSaveDialog(null);
 //   selFile = fc.getSelectedFile();
	 //   File f = new File("first.txt");
    FileReader fr = new FileReader(f);
    BufferedReader br = new BufferedReader(fr);
 
    StringBuffer sb = new StringBuffer();
    String eachLine = br.readLine();
    while (eachLine != null) {
      sb.append(eachLine);
      sb.append("\n");
      eachLine = br.readLine();
    }
 
	 
	
  	  JFrame jF2 = new JFrame("Text Editor"); // Set the window title.
 
      // Set the size of the JFrame to 1150 x 629 pixels. 
      jF2.setSize(1150, 629);
		
		
		JLayeredPane jP2 = new JLayeredPane();
		jP2.setLayout(null);
		
		
	 wordDocModify = new JTextArea(sb.toString(), 5, 10);
		wordDocModify.setLineWrap(true);
		
 
				JButton modifyOpen = new JButton("OPEN");
		           modifyOpen.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) 
						{
 
						}
            });
		
		JButton modifySave = new JButton("SAVE");
  			         modifySave.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) 
						{
						word = wordDocModify.getText();
	 			    try{
    // Create file 
	 
  	 FileWriter first = new FileWriter(new File("first.txt"));
    first.write("First file in java");
	//Close the output stream
	first.close();  
    
 
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
	 		//			FileWriter first = new FileWriter(new File("test.txt"));
			/*	FileWriter fstream = new FileWriter("out.txt");
     			 BufferedWriter out = new BufferedWriter(fstream);
 					   out.write(word);
    //Close the output stream
    out.close(); */
 
						System.out.println("written the following " + word + " to a file");
						}
            });
 
		JButton modifyClose = new JButton("QUIT");
		           modifyClose.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) 
						{
						 System.exit(0);
						}
            });
				
	
		
      // Post the JLabels on the JPanel
	   // jPanel1.add(pictureJLabel); // Post the BSG start screen. 
		jP2.add(wordDocModify, JLayeredPane.PALETTE_LAYER);
		jP2.add(modifyClose, JLayeredPane.PALETTE_LAYER); 
		jP2.add(modifyOpen, JLayeredPane.PALETTE_LAYER);
		jP2.add(modifySave, JLayeredPane.PALETTE_LAYER);
		
		wordDocModify.setBounds(10,20,900,500);
	//	modifyOpen.setBounds(970,50,100,20);
		modifySave.setBounds(970,100,100,20);
		modifyClose.setBounds(970,200,100,20);
 
 
 
      // Post the JPanel into the JFrame
      jF2.getContentPane().add(jP2);
		
      // Displays the JFrame
      jF2.setVisible(true);
}
 
public String test()
{
	
			String word = wordDocModify.getText();
		System.out.println("hey" + word + "test");
		return word;
		
}
 
}

Open in new window

0
Comment
Question by:derricklu
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 24369555
If you use a JEditorPane instead, loading and saving become much easier:
Document doc = ep.getDocument();
ep.getEditorKit().write(fileWriter, doc, 0, doc.getLength());

Open in new window

0
 

Accepted Solution

by:
derricklu earned 0 total points
ID: 24369573
I wanted to do it my way >-<
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24369613
Try
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
 
import java.io.*;
 
import javax.swing.*;
import javax.swing.text.*;
 
 
public class fileio {
    String word;
    JTextArea wordDocModify;
    String openedDoc;
 
    public static void main(String[] args) throws Exception {
        fileio docEdit = new fileio();
        docEdit.textEditorInitialScreen();
 
        //      docEdit.docEditor();
    }
 
    public void textEditorInitialScreen() throws Exception {
        JFrame jF1 = new JFrame("Text Editor"); // Set the window title.
 
        // Set the size of the JFrame to 1150 x 629 pixels. 
        jF1.setSize(1150, 629);
 
        JLayeredPane jP1 = new JLayeredPane();
        jP1.setLayout(null);
 
        JTextArea wordDocNew = new JTextArea(5, 10);
        wordDocNew.setLineWrap(true);
 
        JButton startOpen = new JButton("OPEN");
        startOpen.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //      textEditorEditingScreen();
                    try {
                        textEditorEditingScreen();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });
 
        JButton startSave = new JButton("SAVE");
        startSave.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
 
        JButton startClose = new JButton("QUIT");
        startClose.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
 
        // Post the JLabels on the JPanel
        // jPanel1.add(pictureJLabel); // Post the BSG start screen. 
        jP1.add(wordDocNew, JLayeredPane.PALETTE_LAYER);
        jP1.add(startClose, JLayeredPane.PALETTE_LAYER);
        jP1.add(startOpen, JLayeredPane.PALETTE_LAYER);
        jP1.add(startSave, JLayeredPane.PALETTE_LAYER);
 
        wordDocNew.setBounds(10, 20, 900, 500);
        startOpen.setBounds(970, 50, 100, 20);
        startSave.setBounds(970, 100, 100, 20);
        startClose.setBounds(970, 200, 100, 20);
 
        // Post the JPanel into the JFrame
        jF1.getContentPane().add(jP1);
 
        // Displays the JFrame
        jF1.setVisible(true);
    }
 
    public void textEditorEditingScreen() throws IOException {
        //FileReader dataIn = new FileReader("text.txt");
        String filename = File.separator + "tmp";
        JFileChooser fc = new JFileChooser(new File(filename));
        // Show open dialog
        fc.showOpenDialog(null);
 
        File f = fc.getSelectedFile();
 
        // Show save dialog
        //   fc.showSaveDialog(null);
        //   selFile = fc.getSelectedFile();
        //   File f = new File("first.txt");
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
 
        StringBuffer sb = new StringBuffer();
        String eachLine = br.readLine();
 
        while (eachLine != null) {
            sb.append(eachLine);
            sb.append("\n");
            eachLine = br.readLine();
        }
 
        JFrame jF2 = new JFrame("Text Editor"); // Set the window title.
 
        // Set the size of the JFrame to 1150 x 629 pixels. 
        jF2.setSize(1150, 629);
 
        JLayeredPane jP2 = new JLayeredPane();
        jP2.setLayout(null);
 
        wordDocModify = new JTextArea(sb.toString(), 5, 10);
        wordDocModify.setLineWrap(true);
 
        JButton modifyOpen = new JButton("OPEN");
        modifyOpen.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                }
            });
 
        JButton modifySave = new JButton("SAVE");
        modifySave.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    word = wordDocModify.getText();
 
                    try {
                        // Create file 
                        FileWriter first = new FileWriter(new File("first.txt"));
                        first.write("First file in java");
                        //Close the output stream
                        first.close();
                    } catch (Exception ex) { //Catch exception if any
                        System.err.println("Error: " + ex.getMessage());
                    }
 
                    //                      FileWriter first = new FileWriter(new File("test.txt"));
                    /*      FileWriter fstream = new FileWriter("out.txt");
                            BufferedWriter out = new BufferedWriter(fstream);
                            out.write(word);
                    //Close the output stream
                    out.close(); */
                    System.out.println("written the following " + word +
                        " to a file");
                }
            });
 
        JButton modifyClose = new JButton("QUIT");
        modifyClose.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
 
        // Post the JLabels on the JPanel
        // jPanel1.add(pictureJLabel); // Post the BSG start screen. 
        jP2.add(wordDocModify, JLayeredPane.PALETTE_LAYER);
        jP2.add(modifyClose, JLayeredPane.PALETTE_LAYER);
        jP2.add(modifyOpen, JLayeredPane.PALETTE_LAYER);
        jP2.add(modifySave, JLayeredPane.PALETTE_LAYER);
 
        wordDocModify.setBounds(10, 20, 900, 500);
        //      modifyOpen.setBounds(970,50,100,20);
        modifySave.setBounds(970, 100, 100, 20);
        modifyClose.setBounds(970, 200, 100, 20);
 
        // Post the JPanel into the JFrame
        jF2.getContentPane().add(jP2);
 
        // Displays the JFrame
        jF2.setVisible(true);
    }
 
    public String test() {
        String word = wordDocModify.getText();
        System.out.println("hey" + word + "test");
 
        return word;
    }
}

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:derricklu
ID: 24369643
What did you do?!!?!?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24369674
You had trouble around exception handling in the save action
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24369683
(the variable name of the exception clashed with your event variable name)
0
 
LVL 92

Expert Comment

by:objects
ID: 24369961
fileio.java:158: cannot find symbol
symbol  : constructor FileWriter(java.io.File)
location: class FileWriter
         FileWriter first = new FileWriter(new File("first.txt"));


I don't that error when compiling your code
Your code looks fine in that respect


The problem CEHJ has changed is that the ActionEvent and the Exception var had the same name, though that would ne cause the error you were getting

                  public void actionPerformed(ActionEvent e)
....
    }catch (Exception e){//Catch exception if any


0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
tomcat administrtor 12 68
Java syntax, or is it Selenium 6 39
Notify sent to other threads in Java 9 42
Java pass by reference 3 16
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question