Solved

short procedure for text processing

Posted on 2001-08-13
6
419 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 55
egit plugin on eclipse 8 64
oracle 11g 23 84
Custom Java Application connects to database: Which one of the 20? 4 29
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

803 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