On the command line, give the filename to be displayed.
import java.io.*;
public class Cat {
public static void main (String args[]) {
String thisLine;
for (int i=0; i < args.length; i++) {
try {
FileInputStream fin = new FileInputStream(args[i]);
// JDK1.1+
BufferedReader myInput = new BufferedReader
(new InputStreamReader(fin));
while ((thisLine = myInput.readLine()) != null) {
System.out.println(thisLine);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}With an Applet, we can only open file on the same server that the Applet is coming from.
import java.applet.*;
import java.net.*;
import java.io.*;
public class MyApplet extends Applet {
public void init() {
readFile("mydatafile.txt");
}
public void readFile(String f) {
try {
String aLine = "";
URL source = new URL(getCodeBase(), f);
BufferedReader br =
new BufferedReader
(new InputStreamReader(source.openStream()));
while(null != (aLine = br.readLine())) {
System.out.println(aLine);
}
br.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}The next Applet reads a data file and inserts the data in a Choice component.
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class ReadDataInChoice extends Applet {
Choice myChoice;
public void init() {
myChoice = new java.awt.Choice();
add(myChoice);
readFile("dataforchoice.txt");
}
public void readFile(String f) {
try {
String anItem = "";
URL source = new URL(getCodeBase(), f);
BufferedReader in =
new BufferedReader(new InputStreamReader(source.openStream()));
while(null != (anItem = in.readLine())) {
myChoice.add(anItem);
}
in.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}item 1 item 2 item 3 item 4 item 5 ITEM 6
The following method read a data file and return the content as a String. We use a StringBuffer to optimize string concatenation operations.
private static String readFile(String filename) throws IOException {
String lineSep = System.getProperty("line.separator");
BufferedReader br = new BufferedReader(new FileReader(filename));
String nextLine = "";
StringBuffer sb = new StringBuffer();
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine);
//
// note:
// BufferedReader strips the EOL character
// so we add a new one!
//
sb.append(lineSep);
}
return sb.toString();
}
See this HowTo to read a File which is inside a JAR.
Written and compiled by Réal Gagnon ©1998-2007
[ home ]