Solved

How can I sort the vector by file name (java.io.File object)?

Posted on 2002-04-22
13
1,010 Views
Last Modified: 2008-01-09
Hi,

How can I sort the vector by file name (java.io.File object)?
such as:
uploadFiles.addElement(new java.io.File( tempdir + "\\" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")))
I need the vector of uploadFiles in order of file name.

Thanks!

Hanqing
0
Comment
Question by:hqwu
  • 5
  • 4
  • 2
  • +1
13 Comments
 
LVL 2

Expert Comment

by:coreyit
Comment Utility
replace my Vector with yours. The "natural" sort order for File is my file name.

--------
    Vector v = new Vector();
    v.addElement( new File( "one.txt" ) );
    v.addElement( new File( "two.txt" ) );
    v.addElement( new File( "three.txt" ) );
    v.addElement( new File( "four.txt" ) );
    v.addElement( new File( "five.txt" ) );
   
    TreeSet t = new TreeSet( v );
    Iterator i = t.iterator();
   
    while( i.hasNext() ) {
        System.out.println( ( (File) i.next() ).getName() );
    }
--------

-corey
0
 
LVL 2

Expert Comment

by:coreyit
Comment Utility
Or better, to simply order your existing Vector:

--------
    Vector v = new Vector();
    v.addElement( new File( "one.txt" ) );
    v.addElement( new File( "two.txt" ) );
    v.addElement( new File( "three.txt" ) );
    v.addElement( new File( "four.txt" ) );
    v.addElement( new File( "five.txt" ) );
   
    TreeSet t = new TreeSet( v ); // ordered Set
    v = new Vector( t );          // order the Vector from the Set

    // evidence
    for( int i = 0, x = v.size(); i < x; i ++ ) {
        System.out.println( ( (File) v.get( i ) ).getName() );
    }
--------

-corey
0
 
LVL 2

Expert Comment

by:coreyit
Comment Utility
So, really what you need for your Vector is these two lines. Sorry, still waking up :)

   TreeSet t = new TreeSet( uploadFiles );
   uploadFiles = new Vector( uploadFiles );

-corey
0
 
LVL 19

Expert Comment

by:Jim Cakalic
Comment Utility
You should be able to sort the Vector using:
    Collections.sort(uploadFiles);

The File class implements Comparable with a compareTo method that compares two abstract pathnames lexicographically. The ordering depends on the underlying operating system -- UNIX systems are case-sensitive but Win32 systems are not. The Vector will be sorted "in-place".

Best regards,
Jim Cakalic
0
 
LVL 2

Expert Comment

by:coreyit
Comment Utility
Hmm, that is better!
0
 

Author Comment

by:hqwu
Comment Utility
Thanks for all of your response.

basic need is make sure uploadFiles and filesVec are in
the right order by file names.

filesVec set represents a set of Metaphase data items.  The filename of the java.io.File object (minus the directory path) should match up with the
TrnObjSuggRelativePath attribute on the filesVec
(data item) object.  This needs to be done before
the following call:
ft.performUpload(uploadFiles, filesVec );

More information about uploadfiles:
Vector uploadFiles = new Vector();
for ( i=0; i< filesToUpload.size(); i++)
{
if (FileUtil.getPathFormat(tempdir).equals("UNIX"))
{
uploadFiles.addElement(new java.io.File( tempdir + "/" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")));
}
else
{
uploadFiles.addElement(new java.io.File( tempdir + "\\" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")));
}
}

filesVec declared as:
MTIObjectVector filesVec = new MTIObjectVector (loginContext,uploadFiles.size());
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:hqwu
Comment Utility
Thanks for all of your response.

basic need is make sure uploadFiles and filesVec are in
the right order by file names.

filesVec set represents a set of Metaphase data items.  The filename of the java.io.File object (minus the directory path) should match up with the
TrnObjSuggRelativePath attribute on the filesVec
(data item) object.  This needs to be done before
the following call:
ft.performUpload(uploadFiles, filesVec );

More information about uploadfiles:
Vector uploadFiles = new Vector();
for ( i=0; i< filesToUpload.size(); i++)
{
if (FileUtil.getPathFormat(tempdir).equals("UNIX"))
{
uploadFiles.addElement(new java.io.File( tempdir + "/" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")));
}
else
{
uploadFiles.addElement(new java.io.File( tempdir + "\\" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")));
}
}

filesVec declared as:
MTIObjectVector filesVec = new MTIObjectVector (loginContext,uploadFiles.size());
0
 

Author Comment

by:hqwu
Comment Utility
Thanks for all of your response.

basic need is make sure uploadFiles and filesVec are in
the right order by file names.

filesVec set represents a set of Metaphase data items.  The filename of the java.io.File object (minus the directory path) should match up with the
TrnObjSuggRelativePath attribute on the filesVec
(data item) object.  This needs to be done before
the following call:
ft.performUpload(uploadFiles, filesVec );

More information about uploadfiles:
Vector uploadFiles = new Vector();
for ( i=0; i< filesToUpload.size(); i++)
{
if (FileUtil.getPathFormat(tempdir).equals("UNIX"))
{
uploadFiles.addElement(new java.io.File( tempdir + "/" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")));
}
else
{
uploadFiles.addElement(new java.io.File( tempdir + "\\" + filesToUpload.elementAt(i).getInternalObject().getAttribute("WorkingRelativePath")));
}
}

filesVec declared as:
MTIObjectVector filesVec = new MTIObjectVector (loginContext,uploadFiles.size());
0
 
LVL 1

Expert Comment

by:shahnazali
Comment Utility


hi,
 here is professional approach..... Get the vector .. covert that into array. and sort it using comparator object. subclass of comparator class, u may write ur logic for sorting.

I hope it will work, and u understood this.

bye,
Shaan

====================================================
   public static Vector sortList ( Vector org )
    {
      // copy refence to temp vector....
       Vector temp = (Vector)org.clone() ;
       Object array[] = temp.toArray() ;
       Arrays.sort ( array , new CompareFileByName() );
       return new Vector (Arrays.asList ( array )  ) ;
    }


 static class CompareFileByName implements Comparator
  {
      public int compare(Object o1,Object o2)
       {
        File m1 = (File) o1 ;
        File m2 = (file) o2 ;
         return ( m1.getName().compareTo(m2.getName())) ;
       }
      public boolean equals(Object obj)// not being used
       {
        return false ;
       }
  }
0
 

Author Comment

by:hqwu
Comment Utility
Hi Shaan,
 
    Thanks for your code and suggestion. As suggested from EDS
the file name in upliadFiles (as java.io.File object) which include path (directory)
and the file name in filesVec (as DataItem object, SDRC, now EDS defined) must
be one pair by one pair match before call the following function.

   Sort both uploadFiles (declared as Vector) and filesVec (declared as MTIObjectVector)
is oneway to approach. One pair of file names in the list does not match, then the
ft.performUpload(uploadFiles, filesVec ) will still disorder the file names comparing with
 their contents.

Based your code, I modified as below:


/**
 * Sorts files by names
 */
 public class SortFile {
                     /**
                      * Sorts list for Vector
                      */
                       public static Vector sortList ( Vector org )
                        {
                          // copy refence to temp vector....
                           Vector temp = (Vector)org.clone() ;
                           Object array[] = temp.toArray() ;
                           Arrays.sort ( array , new  CompareFileByName() );
                           return new Vector (Arrays.asList ( array )  ) ;
                        }

                     /**
                      * Sorts list for  MTIObjectVector
                      */
                       public static  MTIObjectVector sortList ( MTIObjectVector org )
                        {
                          // copy refence to temp vector....
                            MTIObjectVector temp = ( MTIObjectVector)org.clone() ;
                           Object array[] = temp.toArray() ;
                           Arrays.sort ( array , new  CompareFileByName() );
                           return new  MTIObjectVector (Arrays.asList ( array )  ) ;
                        }

                     static class CompareFileByName implements Comparator
                      {
                          public int compare(java.lang.Object o1, java.lang.Object o2)
                           {
                           if(o1 instanceof java.io.File)
                            {
                            java.io.File m1 = (java.io.File) o1 ;
                            java.io.File m2 = (java.io.File) o2 ;
                           else if(o1 instanceof DataItem)
                            {
                            DataItem m1 = (DataItem) o1 ;
                            DataItem m2 = (DataItem) o2 ;
                            }
                            else //default as string
                            {
                            String m1 = (String) o1 ;
                            String m2 = (String) o2 ;
                            }
                             return ( m1.getName().compareTo(m2.getName()));
                           }
                      }

}


Any good suggestion is stll welcome, after read some sample from web, I have another approach, please see next comment.

Thanks!
Hanqing
 

0
 

Author Comment

by:hqwu
Comment Utility
Hi all,
based on reference at http://research.compaq.com/SRC/personal/marais/artifacts/java2html/Java2Html.java.html,
I write my own code below: will it work?
(I have not test it yet becau8se of MTIObjectVector need additional classes).

Thanks!

Hanqing

/**
 * @see reference at http://research.compaq.com/SRC/personal/marais/artifacts/java2html/Java2Html.java.html
 */

/**
 * Sorts files by names
 */
 class FileSorter {
    static private Vector dat;
    static private MTIObjectVector MTIdat;
 
    static public void Sort(Vector data) {
        dat = data;
        sort(0, dat.size() - 1);
    }

    static public void Sort(MTIObjectVector data) {
        MTIdat = data;
        sort(0, MTIdat.size() - 1);
    }
   
    static private final long compare(java.lang.Object a, java.lang.Object b) {
        if (a instanceof java.io.File)
            return ((java.io.File)a).name.compareTo(((java.io.File)b).name);
        else // default as string
            return ((String)a).name.compareTo(((String)b).name);
    }
   
    static final void sort(int p, int r) {
        if (p < r) {
            int q = partition(p,r);
            if (q == r)
                q--;
            sort(p,q);
            sort(q+1,r);
        }
    }

    static final int partition (int lo, int hi) {
       if(dat.size() > 1 && MTIdat.size() == 0)
           Vector v = (Vector)dat.clone() ;
      else if(dat.size() == 0 && MTIdat.size() > 1)
           MTIVector v = (MTIVector)MTIdat.clone() ;
      else
           return 0;

        Object pivot = v.elementAt(lo);
        while (true) {
            while (compare(v.elementAt(hi), pivot) >= 0 && lo < hi) hi--;
            while (compare(v.elementAt(lo), pivot) < 0 && lo < hi) lo++;
            if (lo < hi) {
                Object T = v.elementAt(lo);
                v.setElementAt(v.elementAt(hi), lo);
                v.setElementAt(T, hi);
            } else
                return hi;
        }
    }
}

0
 
LVL 1

Accepted Solution

by:
shahnazali earned 120 total points
Comment Utility

Hi,
       I way i told u is almost same as u are specifying. I am using java's built in method to sort. they use quick method.. and i feel, the method u are using in above code is also "quick" sort.  

 U are independent to go for any one, which one suites to u better.

bye,
Shaan
0
 
LVL 19

Expert Comment

by:Jim Cakalic
Comment Utility
Hmm. You could also have done this if you don't like File's natural ordering:

Collections.sort(uploadFiles, new Comparator() {
    public int compare(Object o1, Object o2) {
        if (o1 instanceof File) {
            return ((File)o1).getName().compareTo(((File)o2).getName()));
        } else {
            return ((String)o1).compareTo((String)o2);
        }
      }
});

Seems using the provided Collection-based sort method would be more efficient (and easier IMHO) than doing all that array copying and making new Vectors.

Best regards,
Jim Cakalic
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

772 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

9 Experts available now in Live!

Get 1:1 Help Now