Program to read a file using Applet
Below is the implementation of the above method:
Java
// Java Program to Read // A file using Applet import java.awt.*; import java.applet.*; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; // Driver Class public class FileReaderApplet extends Applet { StringBuilder filecontent = new StringBuilder(); public void init() { // Create a text field for user input TextField fileNameField = new TextField( 20 ); // Create a button to load file Button loadButton = new Button( "Read File" ); loadButton.addActionListener(e -> { String fileName = fileNameField.getText(); readFileAndDisplay(fileName); }); add(fileNameField); add(loadButton); } public void paint(Graphics g) { // String array to store line by line String[] lines = filecontent.toString().split( "\n" ); // Starting vertical position of text field (display field) int y = 40 ; // Display all the lines for (String line : lines) { // Display line g.drawString(line, 20 , y); // Increase the vertical position for the next line y += 20 ; } } private void readFileAndDisplay(String fileName) { try { // Create a File object with fileName File file = new File(fileName); // Create a Scanner to read the file Scanner scanner = new Scanner(file); // Clear previous content filecontent.setLength( 0 ); // Read and concatenate all lines into a StringBuilder with "/n" to identify line break while (scanner.hasNextLine()) { String line = scanner.nextLine(); filecontent.append(line).append( "\n" ); } // Close the scanner scanner.close(); // Repaint the applet to display the content in new lines repaint(); } catch (FileNotFoundException e) { System.err.println( "File not found: " + fileName); e.printStackTrace(); } } } /* <applet code="FileReaderApplet" height="300" width="500"> </applet> */ |
Executing the Program
Text File
w3wiki
A Computer Science portal for geeks. It contains well written, well thought and well
explained computer science and programming articles, quizzes and practice/competitive
programming/company interview Questions
Output
Note: Save the file with .txt extension. Make sure that the text file is in the same folder where you saved the program.
How to Read a File using Applet?
In this article, we will learn how to read the content of the file using Java and display those contents using Applet.
Approach Used
The user should type the name of the file in the input field that asks for the filename in the output applet window. If the file is already present, it will display the content of the file in the output window. Otherwise, it will display that the file is not found by catching the FileNotFoundException handling.