Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2002-04-22
13
Medium Priority
?
1,060 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
ID: 6960797
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
ID: 6960827
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
ID: 6960832
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 6960835
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
ID: 6960845
Hmm, that is better!
0
 

Author Comment

by:hqwu
ID: 6960876
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
ID: 6960904
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
ID: 6960970
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
ID: 6962062


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
ID: 6967533
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
ID: 6967585
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 480 total points
ID: 6967896

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
ID: 6969083
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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 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…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

876 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