How to Write to File Java Applet
A Java applet is a little Java application included in a web page. An applet is written in the Java programming language but can be mixed in with the HTML (Hypertext Markup Language) that makes up the web page. An online test that provides instant results or a simple online Java game embedded into the website are examples of applets. Sometimes the web programmer needs the applet to write information back to a file on the server, such as the results of an online test that the user can save and print out.
Instructions
- 1
Open your HTML file in your web authoring application or a text-editing program. This is the file in which you intend to add the coding for the applet that you want to write to file. An example of a web authoring application is Adobe's Dreamweaver. If using a text-editing program, do not use a word processor like Microsoft Word. Word processors add extra formatting code that the server may not recognize. Use a program like NotePad instead.
- 2
Scroll to the part of the coding where the Java coding begins. Add the right Java classes that will allow you to write to file. To write to a file, use the BufferedWriter, FileWriter and IOException classes.
"import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;"
- 3
Create a Java class that will write to file.
"public class WriteText {
public void writetofile (String file_name) {
BufferedWriter bufferedwriter = null;
try {
bufferedWriter = new BufferedWriter( new Filewriter(file_name));
bufferedWriter.write ("Write this text to the file");
}
}
public static void WriteText(String [] args) {
new WriteText().writetofile("samplefile.txt");
}
}"
The example class above writes the line "Write this text to the file" to a file named samplefile.txt. If you use this code as is, change the text that is to be written to the file and the name of the file that it is writing to.
Tips & Warnings
By default, Java doesn't have permission to write to a file on a web server. You will need a Java Security Policy file on your server.
Add error handling to the code that will execute if any syntax or logical errors keep the code from completing.