What's a good "design pattern" if you want to constantly refer to a file?

I have a file (dictionary.txt) with data field records as follows -

    ABC This represents ...
    PQR This represents ...
    XYZ This represents ...
    ...
    ...
    ... (hundreds of such entries)

      

I have a Java program Searcher.java with the following function

private String[] searchInsideFile(String stringToMatch, String fileName)

      

It looks for the occurrence of any data fields in the file that are contained in the stringToMatch file. However, the function as it is, opens and closes the file each time, and reads all of its hundreds of fields to find a match.

I'll have to call this function many times (maybe hundreds), so I don't think what I'm doing is quite efficient. Is there a good "design pattern" for this situation? Thank you.

+3


source to share


5 answers


If the file is not too large and will not change, you can read its contents on a line at startup, and then just search it



+1


source


If possible, you should preload the entire contents of the file in memory and index it using some data structure defined as an attribute, possibly Map

with appropriate strings. Then the method searchInsideFile

has to look inside the data structure and not load the file at all.



+3


source


The fastest solution is to read the file once and store it in memory. But that's fine if it's not a large file. If the file is too large, or may become too large in the future, you must read it from disk every time, because you have to search for the entire file. Random access won't really help you in this case.

+2


source


I would use the ConstantDataManager template. The basic idea is that there will be an overhead when starting the program, since the object fetches all the information from the file that you use in it as a vector, or nevertheless (Map, etc.) that you want to store.

Then you can do a binary search (assuming your dictionary stores the words in order) on the data store, you can also have a way to store in an object to update any content to a file if you so desire.

A good book to look out for is Software Architecture Design Patterns in Java - Partha Kuchana. Here is a link to the relevant chapter in the book, although you have to pay to see it within 72 hours or buy it from them. You can probably get it from any library or other source ... http://www.crcnetbase.com/doi/pdf/10.1201/9780203496213.ch7

Also have you thought about using a MYSQL database that can make it a little faster if your dictionary contains many entries?

Hope this helps - Ben

+1


source


Perhaps the file in the Searcher class is being used as an instance variable, then create a separate function to open the file. Then modify the searchInsideFile () function to access the previously opened file. Don't forget to close the file after that!

0


source







All Articles