Solved

short procedure for text processing

Posted on 2001-08-13
6
409 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
reasons why a "inside Menu" would not appear for a web server 6 56
oracle 11g 23 49
expectj telnet failing 5 26
eclipse apache tomcat admin console 39 46
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

910 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

22 Experts available now in Live!

Get 1:1 Help Now