Java Example Program / Sample Source Code
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ReadFileFromJarUsingApplet extends Applet implements
ActionListener {
TextArea textarea = new TextArea();
public void init() {
Button button = new Button("Start Reading");
button.addActionListener(this);
setLayout(new BorderLayout());
add(button, BorderLayout.NORTH);
add(textarea, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae) {
try {
// getResourceAsStream() method is using for getting the file from
// JAR as an InputStream:
InputStream inputStream = getClass()
.getResourceAsStream("file.txt");
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
printWriter.println(line);
}
textarea.setText(stringWriter.toString());
repaint();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} |
|
|