|
Previous Next
Doing Character IO
Here we will use the classes FileReader and FileWriter of the package java.io to read from and write to files using character streams. The bytes read or written with these classes are converted to the values that represent Unicode characters used to express text characters. Files that contain readable characters should be processed using character streams. Examples are *.txt and *.htm files. Files that contain unreadable characters should be processed using byte streams, such as *.exe, *.jpg, and *.bmp files.
In our example below, we will also use the classes BufferedReader and BufferedWriter to buffer our input and output. The readLine method of BufferedReader reads a whole line of text. The write of BufferedWriter can write out characters or a portion of a String depending on the parameters given.
The example below shows how to merge a group of files into one.
In the main method, we take the current directory using File(".") and place the list of files in it into an array called contents[]. We then go through each name in contents[] and make sure it is not a directory. If not, we use method, MrgFile, to merge this file into our output. Our output file here is MergeResults.txt. Of course, this can be changed to pick up a filename entered by the user by changing
from FileWriter fileo = new FileWriter("MergeResults.txt");
to FileWriter fileo = new FileWriter(arguments[0]);
We want to make sure we don't merge the output file itself into our output; so we check for it before executing fm.MrgFile(). In MrgFile, we write a header at the top of each file to identify it. After each line we write, we have to force a new line using buffo.newLine().
import java.io.*;
public class FMerge {
void MrgFile(String fname, BufferedWriter buffo) {
try {
FileReader filei = new FileReader(fname);
BufferedReader buffi = new BufferedReader(filei);
String outString;
outString = " <<<<<<<<<< File = " + fname + ">>>>>>>>>> ";
buffo.write(outString, 0, outString.length());
buffo.newLine();
boolean eof = false;
while (!eof) {
String line = buffi.readLine();
if (line == null)
eof = true;
else {
buffo.write(line, 0, line.length());
buffo.newLine();
}
}
buffi.close();
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
}
public static void main(String[] arguments) {
FMerge fm = new FMerge();
try {
FileWriter fileo = new FileWriter("MergeResults.txt");
BufferedWriter buffo = new BufferedWriter(fileo);
File folder = new File(".");
File[] contents = folder.listFiles();
for (int i = 0; i < contents.length; i++) {
String name = contents[i].getName();
if (contents[i].isDirectory() == true)
continue;
if (name.indexOf("MergeResults.txt") != -1)
continue;
if (name.indexOf(".txt") != -1)
fm.MrgFile(name, buffo);
}
buffo.close();
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
}
}
Previous Next
|