10 December 2010

Way of Providing File Permissions to Java Applet

Sometimes if you have ever tried to run the Java Applet, through which you may want to write some data to some specific file on clicking button for example you want to keep track of various user name and passwords and write it to a file, in that case you may get an exception like this

“access denied(java.io.FilePermission filename write”

The reason for this exception is

The Java Platform security does not permit an applet to write to and read from files without explicit permission

A Java Applet has no access to local system resources unless it is specifically granted the access, So here Access permission is granted with a Policy File, and appletviewer is executed with the Policy File to be used for the Applet being viewed.

In order to provide file permissions to an applet ,you have to create a Policy File.

For that Open any Text editor ,say notepad and write the following code

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

Save it as “write.policy” without quotes

Note :- You may also give read permission

Now write code for your applet.If you haven't written till now. See the sample code below

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<Applet code="randomfile" height=400 width=400></applet>*/
public class randomfile extends JApplet implements ActionListener
{
JLabel l1,l2;
JButton b;
JTextField f1,f2;
String str="";
public void init()
{
l1=new JLabel("Username");
l2=new JLabel("Password");
b=new JButton("Submit");
f1=new JTextField(20);
f2=new JTextField(20);
FlowLayout f=new FlowLayout(100,20,25);
Container c=getContentPane();
c.setLayout(f);
b.addActionListener(this);
c.add(l1);
c.add(f1);
c.add(l2);
c.add(f2);
c.add(b);
}
public void actionPerformed(ActionEvent e)
{
Object o=e.getSource();
if(o==b)
{
repaint();
str=f1.getText()+" "+f2.getText();
RandomAccessFile r=null;
try
{
r=new RandomAccessFile("mo.txt","rw");
r.writeBytes(str);
r.close();
}
catch(Exception ee)
{

System.out.println(ee.getMessage());
}
//r.close();
}
}
public void paint(Graphics g)
{
g.drawString(str,100,200);
}
}


The above mentioned code will accept username and password from user and write it to a file mo.txt.

Now for running this applet instead of using normal command ie

appletviewer app.java

You have to use below mentioned command

appletviewer -J-Djava.security.policy=write.policy randomfile.java

It will run properly