Share this page 

Read/write a local file from an Applet (this howto is deprecated)Tag(s): DEPRECATED


(with Netscape capabilities classes)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import netscape.security.*;

public class FileAccess extends Applet 
  implements ActionListener {
  Button loadButton, saveButton;
  TextField filename;
  TextArea  content;
  String browserName;
  boolean securitySupported = false;
         
  public void init() {
    setLayout(new FlowLayout());
    Label label = 
      new Label("Simple file editor");
    add(label);
    loadButton = new Button("Load");
    saveButton = new Button("Save");
    add(loadButton);
    add(saveButton);
    loadButton.addActionListener(this);
    saveButton.addActionListener(this);
    filename = new TextField(20);
    add(filename);
    content = new TextArea(5,20);
    add(content);
    browserName = System.getProperty("java.vendor");
    if (browserName.indexOf("Netscape") > -1)
       securitySupported = true;
    setSize(200, 200);
    }

  public void actionPerformed(ActionEvent evt)  {
    if (securitySupported) {
       if (evt.getSource() == saveButton) {       
          PrivilegeManager.enablePrivilege("UniversalFileAccess");
          try {
             FileWriter aWriter = new FileWriter(filename.getText(), false);
             aWriter.write(content.getText());
             aWriter.flush();
             aWriter.close();            
            }
          catch(Exception e) {
            e.printStackTrace();                
            }
          }
       else if (evt.getSource() == loadButton) {
          PrivilegeManager.enablePrivilege("UniversalFileAccess");
          try {
             BufferedReader aReader  =
                new BufferedReader 
                   (new FileReader(filename.getText()));
             content.setText(aReader.readLine());
             aReader.close();            
            }
          catch(Exception e) {
            e.printStackTrace();                
            }
       }
 
     else {
       getAppletContext().showStatus("security not installed");
       }                     
     }
  }
}