mausam
Posts: 243
Nickname: mausam
Registered: Sep, 2003
|
|
Re: Applet: Writing to File
|
Posted: Sep 19, 2003 5:44 AM
|
|
/**
* WriteFileApplet.java
* DG August 2000
*
* A simple Java 2 Applet which allows a user to enter some text into a TextArea
* and save it to a local file, if security permsisions allow it.
* You can have it write to the working directory , ".\\* in the policy file.
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.io.*;
public class WriteFileApplet extends JApplet implements ActionListener {
private JButton btnWrite;
private JScrollPane sp;
private JTextArea taMessage;
private JTextField tfFileName;
private JPanel pnl;
private String fileName;
public void init () {
fileName = "C:\\test.txt";
// fileName = getParameter("filename");
pnl = new JPanel();
pnl .setLayout(new BorderLayout());
pnl.setBorder(BorderFactory.createEtchedBorder());
tfFileName = new JTextField(fileName);
pnl.add(tfFileName, BorderLayout.NORTH);
// This is how you create a scrollable TextArea in Java 2.
taMessage = new JTextArea();
sp = new JScrollPane(taMessage);
pnl.add(sp, BorderLayout.CENTER);
btnWrite = new JButton("Save text to disk");
pnl.add(btnWrite, BorderLayout.SOUTH);
// The applet has a default content pane in Java 2.
getContentPane().add(pnl);
btnWrite.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj instanceof JButton) {
if(obj == btnWrite) {
File f = new File(tfFileName.getText());
try {
PrintWriter pw = new PrintWriter(new FileWriter(f));
String msg = taMessage.getText();
pw.println(msg);
pw.close();
} catch(IOException ioe) {
System.err.println(ioe.toString());
}
catch (SecurityException se) {
System.err.println(se.toString());
}
}
}
}
public static void main(String args[])
{
WriteFileApplet test = new WriteFileApplet();
test.init();
JFrame frame = new JFrame("Applet");
frame.setContentPane(test);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
|