Link to home
Start Free TrialLog in
Avatar of xiangenhu
xiangenhu

asked on

short procedure for text processing

This must be simple for somebody, but I just started to play with java. Any hints or pointing to helps will be greatly appreciated.

I need to have a simple procedure that read a text file from a given directory, and then process each line (adding, replacing characters).

Thanks a lot!!!
ASKER CERTIFIED SOLUTION
Avatar of Ovi
Ovi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ovi
Ovi

bau
Avatar of Jim Cakalic
Here is a class and associated interface that I have found to be useful for line-oriented stream processing activities. The core class is the StreamEditor which handles all the basic I/O tasks. It is constructed minimally with the objects that represent the input source and output sink. If these are File objects then the class also offers the capability to replace the input file with the output file when the object's close method is invoked.

---------- StreamEditor.java ----------
import java.io.*;

public class StreamEditor {
    private File _inFile;
    private File _outFile;
    private LineNumberReader _in;
    private BufferedWriter _out;
    private boolean _replace;

    public StreamEditor(File inFile, File outFile) throws IOException {
        this(inFile, outFile, true);
    }

    public StreamEditor(File inFile, File outFile, boolean replace) throws IOException {
        _inFile = inFile;
        _outFile = outFile;
        _in = new LineNumberReader(new FileReader(_inFile));
        _out = new BufferedWriter(new FileWriter(_outFile));
        _replace = replace;
    }

    public StreamEditor(Reader in, Writer out) throws IOException {
        _in = new LineNumberReader(in);
        _out = new BufferedWriter(out);
    }

    public void process(StreamProcessor proc) throws IOException {
        if (proc == null) {
            return;
        }

        String line = null;
        if ((line = proc.preProcess()) != null) {
            _out.write(line);
        }
        while ((line = _in.readLine()) != null) {
            if ((line = proc.process(_in.getLineNumber(), line)) != null) {
                _out.write(line);
                _out.newLine();
            }
        }
        if ((line = proc.postProcess()) != null) {
            _out.write(line);
        }
    }

    public void close() throws IOException {
        _in.close();
        _out.flush();
        _out.close();
        if (_replace) {
            _inFile.delete();
            _outFile.renameTo(_inFile);
        }
    }
}
---------- end ----------

The process method of StreamEditor takes a StreamProcessor object. This can be an object of any class that implements the StreamProcessor interface. The three methods required by the interface allow the StreamProcessor to be notified just before processing commences, for each 'line' of data (as defined by BufferedReader.readLine), and at the end of the stream as all processing terminates. Each method is to return a String, the contents of which will be appended to the output stream. The preProcess and postProcess methods will append the Strings as-is. In the case of process, the StreamEditor will also append a platform-dependent line termination sequence. This is because the Reader used to read the line from the input stream originally stripped the line termination prior to it being passed to the method. This means that process could also receive and empty string representing an blank line. In no case should process be passed a null String. If any of the StreamProcessor methods returns null then nothing will be appended to the output stream.

---------- StreamProcessor.java ----------
interface StreamProcessor {
    public String preProcess();
    public String process(int lineNumber, String line);
    public String postProcess();
}
---------- end ----------

Finally, here is a demo class that shows how StreamProcessor can be used. It expects a single command-line argument that specifies the name of the file to process. It inserts one line at the beginning of the file, one line at the end of the file, and prepends to each line of the file its line number.

---------- StreamProcDemo.java ----------
public class StreamProcDemo {
    public static void main(String[] args) throws Exception {
        StreamEditor ed = new StreamEditor(new File(args[0]), new File(args[0] + ".tmp"));
        ed.process(new StreamProcessor() {
            public String preProcess() {
                return "----- BEGIN -----\n";
            }
            public String process(int lineNumber, String line) {
                return lineNumber + ": " + line;
            }
            public String postProcess() {
                return "----- END -----\n";
            }
        });
        ed.close();
    }
}
---------- end ----------

Very trivial, granted, but an effective demonstration, I hope, showing how encapsulation of the I/O responsibilities in the StreamEditor allows you to develop 'transformation' or 'processing' classes that focus on what is to be done to the stream. There are lots of things that could be done to make this better, I suppose. Hope you find it useful enough as is to take and extend.

Best regards,
Jim Cakalic
All,
I am unlocking this question in preparation for cleanup.  I will return in 7 days to finalize this question.  Please leave any recommendations for the final state of this question, I will take all recommendations into consideration.  Failing any feedback, I may decide in 7 days to delete or PAQ this question with no refund.  Thanks.

SpideyMod
Community Support Moderator @Experts Exchange
Me again! I suppose this could go either way as Ovi's answer technically addressed the 'how do I read a file' part of the question. This was a long time ago, but as I recall, my longer response was triggered by the questioner's statement that they were new to Java. I felt a more complete didactic response would be most helpful. Seems like I always do a lot of work for the prospect of only a few points ...

:-)
Jim
answered.  If OVI's answer works and was first in, I've got to give it to OVI, especially since there's no clarification at all from the questioner.  Thanks for letting me know!

SpideyMod
Community Support Moderator @Experts Exchange