Dynamic iteration over collection of files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • najort
    New Member
    • Feb 2008
    • 3

    #1

    Dynamic iteration over collection of files

    Hi
    Let's assume that I have collection of files. That collection of files my vary in future, there might be .class .xml .config etc. I would like to do some task for every of mentioned files. For example for .xml I would like to parse that file, for .config I would like to browse for some properties etc. My goal is to have that open for future changes without modifying previously created methods. My ideal solution is to add new methods (classes) for comming new types of file.


    public List getListFiles(Zi pEntry entry) {
    .............
    return listFiles;
    }

    public void doSthWithFiles( List<File> listFiles) {
    //here is my issue. I don't want to change that method
    every time new file extension is comming. I would like
    to do that by adding new method (class) without midifying that
    method
    }

    Kind Regards
    najort
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by najort
    Hi
    Let's assume that I have collection of files. That collection of files my vary in future, there might be .class .xml .config etc. I would like to do some task for every of mentioned files. For example for .xml I would like to parse that file, for .config I would like to browse for some properties etc. My goal is to have that open for future changes without modifying previously created methods. My ideal solution is to add new methods (classes) for comming new types of file.


    public List getListFiles(Zi pEntry entry) {
    .............
    return listFiles;
    }

    public void doSthWithFiles( List<File> listFiles) {
    //here is my issue. I don't want to change that method
    every time new file extension is comming. I would like
    to do that by adding new method (class) without midifying that
    method
    }

    Kind Regards
    najort
    How about a factory that delivers 'Tasks' given the file extensions. A 'Task' would
    be an interface:

    [code=java]
    public interface Task {
    public void process(File file);
    }
    [/code]

    The factory itself could consult a .properties file like this:

    Code:
    xml   = com.utils.XmlProcessor
    txt   = com.utils.TextProcessor
    # etc.
    Given the extension of the file the factory obtains the name of the corresponding
    class (Class.forName( name).newInstan ce()) and returns it as a Task; voila, you
    can add new classes for new file extensions. All you have to do is write the class
    and list it in the .properties file.

    kind regards,

    Jos

    Comment

    • najort
      New Member
      • Feb 2008
      • 3

      #3
      Great Thanks
      This is the solution I was waiting for.
      Very quick and good.
      Thanks again

      Comment

      Working...