Please send questions to
st10@humboldt.edu .
// how hard is it to simply write to a (text) file?
//
// last modified: 11-2-00
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class TryWriteToFile
{
public static void main(String args[])
{
TryWriteToFileFrame thisFrame = new TryWriteToFileFrame();
thisFrame.setSize(600, 400);
thisFrame.setTitle("Trying to Simply Write to a File");
thisFrame.show();
}
}
class TryWriteToFileFrame extends JFrame implements ActionListener
{
JLabel title, fileToWriteLabel;
JTextArea fileContents;
JTextField fileToWriteField;
JScrollPane fileContentsPane;
public TryWriteToFileFrame()
{
Container myContentPane;
myContentPane = getContentPane();
myContentPane.setLayout(new FlowLayout());
// gracefully handle a window closing event
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
// this text area will hold names of files in current
// directory; it is within a JScrollPane to provide
// scrolling capabilities?
fileContents = new JTextArea(10, 20);
fileContentsPane = new JScrollPane(fileContents);
myContentPane.add(fileContentsPane);
fileToWriteLabel = new JLabel("type new file name: ");
myContentPane.add(fileToWriteLabel);
fileToWriteField = new JTextField(20);
fileToWriteField.addActionListener(this);
myContentPane.add(fileToWriteField);
}
// when a file name is entered into textfield,
// either complain or write textarea contents to
// that filename in the current directory
public void actionPerformed(ActionEvent e)
{
String fileToWriteName;
File fileToWrite;
// another java.io option... made for writing text files in
// particular (as opposed to binary files)
FileWriter toStream;
fileToWriteName = fileToWriteField.getText();
fileToWrite = new File(fileToWriteName);
// is this currently a file name? No good if so!
if (fileToWrite.exists())
{
fileToWriteField.setText("try again --- file " +
fileToWriteName + " exists");
}
else
{
try
{
// instantiate FileWriter stream toStream,
// use its write() method to write contents
// of textarea to desired file.
//
// do not forget to close the file!
toStream = new FileWriter(fileToWrite);
toStream.write(fileContents.getText());
toStream.close();
fileToWriteField.setText("");
}
catch (FileNotFoundException exc)
{
// a failed opening of a file (a failed attempt
// to instantiate toStream, above) could
// throw a FileNotFoundException
System.out.println("TryWriteToFile2: Could not open: "
+ fileToWriteName);
}
catch (IOException exc)
{
System.out.println("TryWriteToFile: IOError: " +
exc.getMessage());
}
}
}
}