Solved

short procedure for text processing

Posted on 2001-08-13
6
398 Views
Last Modified: 2012-05-04
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!!!
0
Comment
Question by:xiangenhu
  • 2
  • 2
  • 2
6 Comments
 
LVL 9

Accepted Solution

by:
Ovi earned 50 total points
ID: 6382905
This method reads each line from the passes filename and store'it in a Vectorwhich is returned in the end. Your text processing should be done on this Vector. As an optimization, if your needs permit this, in the while cycle after each line is readed, you can process'it.

import java.io.*;
import java.util.*;
..........................
public Vector readFile(String aFile) {
Vector lines = new Vector();
try {
  BufferedReader br = new BufferedReader(new FileReader(aFile));
  String line = "";
  while((line = br.readLine()) != null)
    lines.addElement(line);
} catch(Exception e) {}
return(lines);
}
......................
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6387853
bau
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 6389026
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
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Expert Comment

by:SpideyMod
ID: 8289634
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
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 8292466
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
0
 

Expert Comment

by:SpideyMod
ID: 8336451
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
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now