Munging Text Files
MungeTest.java
To process a text file line-by-line, we can use BufferedReader and PrintWriter:
BufferedReader
|
+ BufferedReader(Reader)
+ readLine() : String
|
PrintWriter
|
+ BufferedReader(OutputStream)
+ print(Object or primitive)
+ println(Object or primitive)
|
BufferedReader.readLine() returns null at the EOF.
PrintWriter's print() and println() are overloaded to handle all primitive types,
as well as String and arbitrary Object types:
boolean
char char[]
double float
int long
String Object
(PrintWriter prints Objects by calling their toString() method)
|
import java.io.*;
public class MungeTest {
static final String INFILE = "index.html";
static final String OUTFILE = "index.txt";
public static void main(String[] args) {
try {
munge();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void munge() throws IOException {
BufferedReader reader = new BufferedReader(
new FileReader(INFILE));
PrintWriter writer = new PrintWriter(
new FileWriter(OUTFILE));
String line;
while ((line = reader.readLine()) != null) {
line = mungeLine(line);
writer.println(line);
}
reader.close();
writer.close();
}
private static String mungeLine(String line) {
return line.toUpperCase();
}
}
|
|