Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Applet Write Files Example

                         

In this section, you will learn how to write to a file from an applet. This is very simple but the security manager don't provide the permission for writing a file from an applet. For this, you will have to maintain a Java security policy file that will allow the granted permission for writing a file from an applet. Without maintaining the Java security policy file, the security manager naturally installed during startup whenever an applet is started in the Java based web browser. By default the file writing permission is not allowed. All the permissions are allowed or disallowed in the policy file after that you write it or not.

Description of program:

The following program or code helps you in writing the content in a file from an applet. First of all this program creates a class (WriteFile) to extends the Applet class. After that, this program constructs a GUI layout that contains text field, text area and a command button. The text field has the name of file that have to be written and the text area provides a area for writing the user text that have to write in the given file. The common button performs your action ( for writing ). When you will run it (use the appletviewer -J-Djava.security.policy=po.policy WriteFileApplet.html), the GUI appears on the screen that takes the file name and text (content) on the specified locations. Without giving it, a message will appear on the screen in the message box (Please enter file name!). If the file name is entered without any text, even though it will  display a message in the message box (Please enter your text!). You have entered both and click the "WriteToFile" command button, the file name is checked out. Whenever the file isn't exists, it will display a message in the message box (File not found!) and if the given file exists, the given text are written into the file and it will show a message in the message box (Text is written in vk.shtml) otherwise not and shows a message in the message box (Text  isn't written in vk.shtml). You will try it.

Here is the code of program (WriteFile.java):

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import java.net.*;

public class WriteFile extends Applet{
  Button write = new Button("WriteToFile");
  Label label1 = new Label("Enter the file name:");
  TextField text = new TextField(20);
  Label label2 = new Label("Write your text:");
  TextArea area = new TextArea(10,20);
  public void init(){
    add(label1);
    label1.setBackground(Color.lightGray);
    add(text);
    add(label2);
    label2.setBackground(Color.lightGray);
    add(area);
    add(write,BorderLayout.CENTER);
    write.addActionListener(new ActionListener (){
      public void actionPerformed(ActionEvent e){
        new WriteText();
      }
    });
  }
  public class WriteText {
    WriteText(){
      try {
        String str = text.getText();
        if(str.equals("")){
          JOptionPane.showMessageDialog(null,"Please enter the file name!");
          text.requestFocus();
        }
        else{
        File f = new File(str);
        if(f.exists()){
          BufferedWriter out = new BufferedWriter(new FileWriter(f,true));
          if(area.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Please enter your text!");
            area.requestFocus();
          }
          else{
            out.write(area.getText());
            if(f.canWrite()){
              JOptionPane.showMessageDialog(null,"Text is written in "+str);
              text.setText("");
              area.setText("");
              text.requestFocus();
            }
            else{
              JOptionPane.showMessageDialog(null,"Text isn't written in "+str);
            }
            out.close();
            }
          }
          else{
            JOptionPane.showMessageDialog(null,"File not found!");
            text.setText("");
            text.requestFocus();
          }
        }
      }
      catch(Exception x){
        x.printStackTrace();
      }
    }
  }
}

Download this code.

For running an applet you have to need an HTML file that uses the applet class to run this in the Java based web browser.

Here is the HTML code (WriteFile.html):

<HTML>
<HEAD>
<TITLE>
Write file example </TITLE>
<applet code="WriteFile.class", width="200",height="300">
</applet>
</HEAD>
</HTML>

This is the policy file that allowed the permissions to the user for writing or reading the file from an applet.

Here is the code of policy file (WriteFile.policy):

grant {
permission java.io.FilePermission "<<ALL FILES>>","write";
};

Output of program:

Compile and run:

C:\vinod\applet>javac WriteFile.java

C:\vinod\applet>appletviewer -J-Djava.security.policy=WriteFile.policy WriteFile.html

appletviewer:
This is the command that allows you for running the applets outside of a web browser.

-Jjavaoption:
The javaoption is a single argument string to the Java interpreter that runs the appletviewer. This argument hasn't spaces, if the argument contains the multiple words must be begin with '-J' prefix that is stripped and useful for adjusting the execution of compiler environment or memory usage.

If file name is blank:

If Text area is blank:

Both are written:

Message Box:

Get the written file:     
vk.shtml

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

5 comments so far (
post your own) View All Comments Latest 10 Comments:

Hi,
This is a great article, and worked like a charm in a very first attempt. Even though I dont have a lot of experience in Applet am able to write to file succesfully.

I do have one further request, Can you please let me know if this applet can be called with out the AppletViewer (i mean directly from html). I am currently able to load WriteFile.html, but the write request did'twork(though it did not give any error).

Currently the AppletViewer is taking care of associating the policy file, and I dont know how I can associate the WriteFile.policy with the applet call.

Thanks

Posted by venu on Thursday, 10.9.08 @ 13:46pm | #80976

i have tried to access data from MS Access but i am unable to access it from applet. To access data from MS Access in applet i have used same part of code as in frames but geting an error "access denied".. can you please guide me.

Posted by sam on Wednesday, 03.26.08 @ 15:15pm | #54388

Hi,

This is a great tutorial. I know this work in an applet viewer, but I am trying to get it to work TRHOUGH a web browser. Your READ an applet works fine through a broswer, but this write one does not seem too.

Any ideas how I can write to a file, but using the applet through a web browser?

Thanks!

Posted by Michael on Thursday, 02.14.08 @ 01:35am | #48195

thnaks man for this wonderful tutorial........u solved a long standing problem of mine.....keep up the good work

Posted by sudip on Saturday, 10.20.07 @ 19:05pm | #34459

Hi there!

Is it possible to write a file from applet using Url connection as we can see at reading?
I have tried the folowing lines:

URL url = new URL(getCodeBase(), "name.txt");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
OutputStream out = urlConn.getOutputStream();

The problem is the getOutputStream().
It is throws UnknownServiceException: protocol doesn't support output

Do you have any idea to handle this exception?

Thank you for your help in advance.

I am looking forward your answer.

Best Regards,
Szabolcs

Posted by Szabolcs Szlavik on Sunday, 09.30.07 @ 23:34pm | #30794

Latest Searches:
create box in excel sh
poc dojo container
д??????д?????д????Ð
save image to file
PHP Introduction to PH
list switch
lucene in windows
binary recursio
java program to arrang
print values from tabl
java math random
Photoshop Text Effect
list box code in jsp
what do u mean by java
MULTIPLE SELECT COMBO
flex pure mvc
PHP Miscellaneous Css
objective
How to use string vali
Wireless
pst.setInt()
xml to telnet
loading combo values f
convert object into da
show calender page
Web Design Basics Mike
bean:define tags
sort compareTo
3DS MAX Effects Easy s
Linux Caixa Mпâ? ?пâ
XML READER
Ajax Examples
sun jdbc
get windows directory
Create PDF in a Browse
code of image upload i
find char in a string
textbox
books available in bas
Image with mouse drag
get data by using char
insert date with java
varStatus
program to increase si
include a file in dire
character in javascrip
create menubar
JSON AJAX
header footer menu bod
iterator
browse button in html
unicode
insert data to text fi
difference between inc
Insert Data in Table U
core java
Store Procedure in hib
Database MySQL Using S
Error handling in stru
difference between com
Photoshop Effects Shin
determinan
Interview question on
JSF action lestner exa
JSFpanelGridTag
Convert String to Bool
reflection api
3DS MAX Modeling Model
decimal to extended as
JQUERY
how can we select an d
insert coding of autoi
Read a file in java
Combattons la programm
Photoshop Digital Art
java nodequeue tutoria
dynamic insert value J
shell
ajax auto complete
hybernet
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.