Sort array(list) of files on filename

Hey all,
Is there a way to sort an array(list) of files on the names of those files. (the files are not in same directory)
Thanks

Gogoe wrote:
Hey all,
Is there a way to sort an array(list) of files on the names of those files. (the files are not in same directory)
Thanks
Why do you need to sort the actual Files? Can't you just sort the list of name using Arrays.sort()? Once the names are in order you call up the Files in the order you read the names. Or is there more to the request yet?

Similar Messages

  • Sorting array list

    can u please give me the source code for:
    sorting array list for ascending and descending order

    You already have the source code.

  • Sort array list and using comparable

    With the following code I would like to setup a score object for the current player.
    Change it to a string(Is it correct to say parse it to a string type)
    Then add it to the arraylist.
    So I can sort the array list according to the string size.
    That's why I have the variables in that order.
    So if 3 players have the same amount of guesses, they can be positioned on the high score list according to their gameTime.
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);So the error message says " The method add(Score) in the type arrayList <Score> is not applicable for the arguments(string)"
    Now, I understand that, I would like to know if there is another way to achieve what I am trying to do.
    Is the string idea I am trying here possible? is it practical or should I use comparable?
    I have looked at comparable, but I don't get it.
    Will my Score class implement comparable. I am looking at an example with the following code.
    Employee.java
    public class Employee implements Comparable {
        int EmpID;
        String Ename;
        double Sal;
        static int i;
        public Employee() {
            EmpID = i++;
            Ename = "dont know";
            Sal = 0.0;
        public Employee(String ename, double sal) {
            EmpID = i++;
            Ename = ename;
            Sal = sal;
        public String toString() {
            return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
        public int compareTo(Object o1) {
            if (this.Sal == ((Employee) o1).Sal)
                return 0;
            else if ((this.Sal) > ((Employee) o1).Sal)
                return 1;
            else
                return -1;
    ComparableDemo.java
    import java.util.*;
    public class ComparableDemo{
        public static void main(String[] args) {
            List ts1 = new ArrayList();
            ts1.add(new Employee ("Tom",40000.00));
            ts1.add(new Employee ("Harry",20000.00));
            ts1.add(new Employee ("Maggie",50000.00));
            ts1.add(new Employee ("Chris",70000.00));
            Collections.sort(ts1);
            Iterator itr = ts1.iterator();
            while(itr.hasNext()){
                Object element = itr.next();
                System.out.println(element + "\n");
    }The thing I don't understand is why it returns 0, 1 or -1(does it have to do with the positioning according to the object is being compared with?)
    What if I only use currentScore in a loop which loops every time the player restarts?
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);Also why there is a method compareTo, and where is it used?
    Thanks in advance.
    Edited by: Implode on Oct 7, 2009 9:27 AM
    Edited by: Implode on Oct 7, 2009 9:28 AM

    jverd wrote:
    Implode wrote:
    I have to hand in an assignment by Friday, and all I have to do still is write a method to sort the array list. Okay, if you have to write your own sort method, then the links I provided may not be that useful. They show you how to use the sort methods provided by the core API. You COULD still implement Comparable or Comparator. It would just be your sort routine calling it rather than the built-in ones.
    You have two main tasks: 1) Write a method that determines which of a pair of items is "less than" the other, and 2) Figure out a procedure for sorting a list of items.
    The basic idea is this: When you sort, you compare pairs of items, and swap them if they're out of order. The two main parts of sorting are: 1) The rules for determining which item is "less than" another and 2) Determining which pairs of items to compare. When you implement Comparable or create a Comparator, you're doing #1--defining the rules for what makes one object of your class "less than" another. Collections.sort() and other methods in the core API will call your compare() or compareTo() method on pairs of objects to produce a sorted list.
    For instance, if you have a PersonName class that consists of firstName and lastName, then your rules might be, "Compare last names. If they're different, then whichever lastName is less indicates which PersonName object is less. If they're the same, then compare firstNames." This is exactly what we do in many real-life situations. And of course the "compare lastName" and "compare firstName" steps have their own rules, which are implemented by String's compareTo method, and which basically say, "compare char by char until there's a difference or one string runs out of chars."
    Completely independent of the rules for comparing two items is the algorithm for which items get compared and possibly swapped. So, if you have 10 Whatsits (W1 through W10) in a row, and you're asked to sort them, you might do something like this:
    Compare the current W1 to each of W2 through W10 (call the current one being compared Wn). If any of them are less than W1, swap that Wn with W1 and continue on, comparing the new W1 to W(n+1) (that is, swap them, and then compare the new first item to the next one after where you just swapped.)
    Once we reach the end of the list, the item in position 1 is the "smallest".
    Now repeat the process, comparing W2 to W3 through W10, then W3 to W4 through W10, etc. After N steps, the first N positions have the correct Whatsit.
    Do you see how the comparison rules are totally independent of the algorithm we use to determine which items to compare? You can define one set of comparison rules ("which item is less?") for Whatsits, another for Strings, another for Integers, and use the same sorting algorithm on any of those types of items, as long as you use the appropriate comparison rules.Thanks ;)
    massive help
    I understand that now, but I am clueless on how to implement it.
    Edited by: Implode on Oct 7, 2009 10:56 AM

  • Sort Array List

    Hi,
    I have an array List which have values like empid, amount, corpcode eg.
    223, 345.95, SDB
    791, 567.75, XYZ
    115, 345.95, SDB
    I need to sort this array like this
    115, 345.95, SDB
    223, 345.95, SDB
    791, 567.75, XYZ
    How can I do this?
    Thanks

    You have to implement a natural order for your object, so that it can be sorted. There are a lot of tutorials out there for this, but I will do it anyway for you:
    public YourClass implements Comparable<YourClass>{
    int firstNumber;
    int secondNumber;
    int thirdNumber;
    String someIdentifier;
    public int compareTo(YourClass otherObject){
       int difference = this.firstNumber - otherObject.firstNumber;
       if(difference != 0) return difference;
       difference = this.secondNumber - otherObject.secondNumber;
       if(difference != 0) return difference;
       return this.someIdentifier.compareTo(otherObject.someIdentifier);
    }As you can see, the basic idea is, that you return if an object is greater, equal or less than another. You begin with the most important criteria. If this one is equal, you check the next one.
    Some objects already include the comparable interface, like String. If this is the case, you can take advantage of this, and use their compareTo Method.
    After this, you can sort your objects with
    Collections.sort(someList);

  • How to write array list to file ?

    Hi everyone,
    I got a arraylist binaryEncodedData and I want to write to file. how do I make it into a HexString ? I had tried to convert it this way and it doesn't work. I try to print out the temp value but there was nothing . Please help, thanks
    byte[] bytes = new byte[binaryEncodedData.size()];
    String temp;
    for(int i=0;i<binaryEncodedData.size();i++)
         bytes[i] = (byte)binaryEncodedData.get(i);
    for(int i=0;i<bytes.length;i++)
         //System.out.println(Integer.toHexString(bytes[i] & 0X00FF));
         temp.concat(Integer.toHexString(bytes));
    System.out.println("Temp = " + temp);

    Strings are immutable. The correct way to get anything to print out is this:
    for(int i=0;i<bytes.length;i++)
    //System.out.println(Integer.toHexString(bytes & 0X00FF));
    temp = temp.concat(Integer.toHexString(bytes));
    }I'm not sure why you want this in Hex, but if it is not a requirement standard serialization would be easier.

  • How to Sort music on play list by FILE NAME?

    How to Sort music on play list by FILE NAME?

    iTunes doesn't display the filename or filepath as a column so you can't sort on it. I could write a script to copy the filepath into the Sort Name field so that sorting by name would sort by filepath. Would that help? In normal circumstances however filepath order would be the same as Album by Artist, so I'm not sure what you would gain. Perhaps there is another way to approach whatever problem you think sorting by filename would solve.
    tt2

  • Adding two array lists together and a text file to an array list

    I'm having problems coding these two methods... Could someone explain how to do this? I can't find information on it anywhere... :(
    "MagazineList" is the class I'm coding in right now, and I already declared "list" as an array list of another class called "Magazine".
    public boolean addAll(MagazineList magazines)
           if (list == magazines) {
               return false;
            else {
                list.addAll(magazines);
           return true;
       public boolean addAll(String filename)
           Scanner in = ResourceUtil.openFileScanner(filename);
            if (in == null) {
               return false;
            String line = source.nextLine();
            while (!line.equals("")) {
              list.add(Magazine(source));
           in.close();
       }

    I assume "addAll(MagazineList magazines)" is defined in the MagazineList class?
    Then,
    list.addAll(magazines);probably needs to be something like:
    list.addAll(magazines.list);This uses the private variable ( should be private) list from the input MagazineList, and adds all of those Magazine objects to the list in the current MagazineList.
    But, yes, describe your problems more clearly, and you'll get better answers more quickly (because people will be able to understand you and give you a suggestion without asking you another question first).

  • Operating on a list of files with spaces in the filenames

    I am writing a script that operates on all files within a directory structure. I want to pass the full filename and path to the commands in the script. I am using a for loop to do this. Unfortunately, I don't know how to get the "for" line to pass this info properly.
    I have the following items on the desktop:
    a folder with a lot of spaces in its filename
    file1
    file2
    file3
    If I run
    for i in $( find * /Users/<username>/Desktop/ ) # where <username> = the correct shortname
    I get:
    Desktop/a
    folder
    with
    a
    lot
    of
    spaces
    in
    its
    filename
    Desktop/file1
    Desktop/file2
    Desktop/file3
    If I run:
    for i in "$( find * /Users/<username>/Desktop )"
    I get every full path for each file on the Desktop, but they're all run together on a single line as below:
    Desktop/a folder with a lot of spaces in its filename Desktop/file1 Desktop/file2 Desktop/file3
    How do I get the following output?
    Desktop/a folder with a lot of spaces in its filename
    Desktop/file1
    Desktop/file2
    Desktop/file3

    Actually I tend to avoid loops like the plague. Don't know why, and of course you can't always do that …
    Something piped into a *while read variable* loop is one of my favorite things to do in a shell script, especially throw-away scripts:
    find * /Users/<username>/Desktop/ | while read file
    do
    [[ "$file" = .app/ ]] && continue
    echo "$file"
    done
    It gives me tons of control. I've started with a simple one-off throw-away script to do something quick, and find it so useful that I add things, and eventually I end up with a 5,000 line utility that I cannot live without. All from a simple while loop.
    My other favorite throw-away script is where I have a list of objects (often a list of files). I use a here document on those:
    while read file
    do
    if ! gvimdiff -f $file /path/to/prev/version/$file; then
    exit # :cq will cause a non-zero gvimdiff exit code
    fi
    done <<EOD
    file1.c
    file2.c
    file3.c
    EOD

  • Input data file into an Array List using scanner

    How would i input the data into a new array list with fields iD, name, acc_No, balance, oDLimit.
    the data looks like this;
    10 10 is included in the data and i can only assume is the size of the array/data to be put in
    1/J.Lewis/00-1456/250.54/200
    3/T.Standish/01-5682
    1/W.Loftus/01-9356/309.43/400
    So far i have
    public static void main(String[] args) {
            ArrayList <BankAccount> CurrentAccounts = new ArrayList <BankAccount>();
            Scanner filescan = null;
            try
                filescan = new Scanner(new File("BankAccountInput"));
            catch(Exception e)
                System.out.println(e);
            }Any help would be great, thanks!

    split

  • Tasks re-sorting in the MPP file when synching with SharePoint task list

    When synchronizing the MPP file with the ShPt task list, we have seen tasks re-sorting in the MPP file.  Very annoying, especially with schedules with a large number of tasks.  Just wondering if anyone has experienced this issue, and if you
    could point me in the right direction for solving it.  FYI, listing below my signature the columns we are synchronizing (in case you know of an issue with one or more of these).
    FYI, we are using MS Project 2013 Pro and SharePoint 2010.  We tried using the synch feature with MSP 2010 and it did not seem to be available.
    Greatly appreciate your help on this topic.  Sincerely,
    Michael.
    Columns to map:
    Text30
    Text15
    Baseline Start
    Baseline Finish
    Duration
    Baseline Duration
    Baseline Work
    % Work Complete
    Flag8
    Critical
    Number5
    Text19
    Work
    Actual Start
    Actual Finish
    Columns to uncheck:
    Priority
    Task Status

    Hi,
    The resource is created as a new resource with no security group and no loggin account, meaning it is strictly a resource and not a user. So this resource can be assigned on others projects but cannot connect to PS in any way (thus does not consume a CAL)
    unless you convert it into a user by adding a valid account and a security group.
    Hope this helps,
    Guillaume Rouyre, MBA, MCP, MCTS |

  • Help with using mergesort to sort a list of names alphabetically?

    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this code and when I trace it through on paper with an example array of names, it should work, but when I run it with an actual txt file, it's not correctly alphabetical.
    I'd appreciate it if someone could take a look at my code and give me some ideas on what my problem might be.
    Thanks in advance! (note: I also posted this question to java-forums.org, as I've been working on this little problem for over five hours and am in desperate need of some help!)
    public static void mergeSort(String[] names) 
            if (names.length >= 2) 
                String[] left = new String[names.length/2]; 
                String[] right = new String[names.length-names.length/2]; 
                for (int i = 0; i < left.length; i++) 
                    left[i] = names;
    for (int i = 0; i < right.length; i++)
    right[i] = names[i + names.length/2];
    mergeSort(left);
    mergeSort(right);
    merge(names, left, right);
    // pre : result is empty; list1 is sorted; list2 is sorted
    // post: result contains result of merging sorted lists;
    // add merge method below
    public static void merge(String[] names, String[] left, String[] right)
    int i1 = 0;
    int i2 = 0;
    for (int i = 0; i < names.length; i++)
    if (i2 >= right.length || (i1 < left.length && left[i1].compareToIgnoreCase(right[i1])<0))
    names[i] = left[i1];
    i1++;
    } else
    names[i] = right[i2];
    i2++;

    Welcome to the forum.
    Please read this to learn hot to format your code (and other things relevant for this forum):
    https://forums.oracle.com/forums/ann.jspa?annID=1535
    923566 wrote:
    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this codeDo you know the <tt>TreeSet</tt> class?
    http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
    With that sorting Strings is a two liner:
    http://www.java2s.com/Code/Java/Collections-Data-Structure/TreeSetDemo.htm
    bye
    TPD

  • Writing an integer array to a file...

    Okay, so I just wanna write a sorted integer array to file... but I'm having a problem or two.
    int[] array = read(new File("C:\\college work\radixsort.txt");
    radixSort(array, array.length);That text file is a list of 30 numbers.
    After the radixSort method is called the values in the text file are sorted into the correct order. Then I want to write the sorted values to a text file radixSorted.txt
    I had too many problems with printArray() so I figured this could be easier.
    I have tried FileInputStream and FileWriter but no luck.
    I don't want the answer, but just something to help point me in the right direction.
    Thank you.

    pri.println(char[] x) looks like the one I am looking for.
    I have modified the code. I've placed only the println part inside the loop now, but it's just the pri.println(char[], array) now. I'm nearrrrly there! (I think).
    try
                   PrintWriter pri = new PrintWriter(new FileWriter("C:/college work/radixsort.txt", true));
                   for (int h = 0; h < array.length; h++)
                        pri.println(char[], array);
              catch (Exception e)
                   e.printStackTrace();
                   System.out.println("No such file exists.");
              finally
                   pri.close();
              }Edited by: JayJay88 on Nov 8, 2008 1:16 PM

  • List of Files in a directory

    Is there a way that you can get a list of files in a directory that are spelt a certain way? Ex. If in a directory there are html files, txt files, et, In java can I get *.html or a html file with certain text in the name? java.html??
    How you can Help
    US101

    here are the code to list your files
         File startDir = new File("your directory goes here" );
         File[] dirList = startDir.listFiles();
         if (startDir.isDirectory());
         out.print( startDir.getPath() );
              //Start cycling through the array for the file
         for ( int count = 0; count < dirList.length; count++ )
    String fileName = dirList[count].getName();
              int index = fileName.lastIndexOf('.');
              String newString = null;
                   if (index >= 0)
                        newString = fileName.substring(index, fileName.length());
                        if ( newString.equalsIgnoreCase( ".txt"))
                             if ( dirList[count].isDirectory())
                                  out.println( dirList[count].getName() );
                             else
                                  out.println( dirList[count].getName());
                             }//end else
                        }// end if newstring
         }//end if index
         }//end for

  • Can't create file with filename contains user-defined character

    Dear all,
    I got a question about directory listing and file creation. My development OS is Win2K traditional chinese version and my JDK is 1.4.0 Internationation version.
    My program copy each of file into another directory. I call File.lists() to get an array of filename String, I then create the file in the destination directory. However, I got error while the filename contains some chararters that I created in my system only by Win2K character creation utility. I found those characters become "?" if I printf them. How could I overcome this problem? Thanks.
    ArthurPan

    The limitation here is not caused by Java at all.
    Java handles UNICODE characters, the concept of ASCII characters is only loosely retained by accident, mainly because the ASCII set is retained as is in UNICODE.
    The limitation here is the Operating System whose filesystem does not support UNICODE names. As far I as can remember, although the System default locale can be your language equivalent, the filesystem does not necessarily support UNICODE filenames even though it may actually be able.
    What you need to do is check the file.encoding property in Java and set that using the -Dfile.encoding=BIG-5 or whatever when starting your application. This may help with the file name problem.

  • Need help finding the sum of an array list

    I'm making a mock up of iTunes, I suppose, for class. My only issue is that I can't figure out how to add all the durations of each sound file when it's stated in the array.
    I've put the part I'm having trouble with in bold, it is located in the Jpod class. We're using a program called BlueJ for coding, which is why the commenting is slightly odd.
    import java.applet.*;
    import java.io.*;
    import java.net.*;
    public class SoundPlayer
        public SoundPlayer(String fileName, int duration)
            AudioClip testClip;
            URL testUrl;
            System.out.println("Playing " + fileName);
            try{
                testUrl=new URL("file:" + new File(".").getCanonicalPath() + "/" + fileName);
                testClip=Applet.newAudioClip(testUrl);
                testClip.play();
                Thread.sleep(duration*1000);
                testClip.stop();
            }catch(Exception e){ System.out.println(e.toString()); }
    public class Sound
        private String author;
        private String fileName;
        private int duration;
         * Constructor for objects of class Sound
        public Sound(String newAuthor, String newFileName, int newDuration)
            // initialise instance variables
            author = newAuthor;
            fileName = newFileName;
            duration = newDuration;
         * Returns the duration of the sound file
         * @return     duration of the sound file
        public int getDuration()
            // returns duration
            return duration;
         * Returns the author of the sound file
         * @return     author of the sound file
        public String getAuthor()
            //returns author
            return author;
         * Prints the author, filename, and duration
        public void printSound()
            System.out.println("Author: " + author + " File name: " + fileName + " Duration: " + duration);
         * Plays the sound
         * @return     sound file
        public void playSound()
            new SoundPlayer("Lab4.wav",3);
    import java.util.ArrayList;
    import java.util.Iterator;
    public class Jpod
        // instance variables - replace the example below with your own
        private ArrayList<Sound> playlists;
         * Constructor for objects of class Jpod
        public Jpod()
            playlists = new ArrayList<Sound>();
         * Adds a sound to the playlist
         * @param  sound   of type Sound
        public void addSound(Sound sound)
            // inserts the sound into the playlist
            playlists.add(sound);
         * Adds 3 sounds to a playlist
        public void createPlayList()
            Sound s;
            s = new Sound("Microsoft", "Lab4.wav", 2);
            addSound(s);
            s = new Sound("Dr. Evil", "DrEvil.wav", 4);
            addSound(s);
            s = new Sound("Arnold Schwarzenegger", "Terminator.wav", 2);
            addSound(s);
         * Remove desired sound object
         * @param indexNumber The number of the sound object to be removed
        public void removeSound(int indexNumber)
            if(indexNumber < 0){
                //Not a valid index number - do nothing
            else if(indexNumber < playlists.size()){
                //Valid indexNumber
                playlists.remove(indexNumber);
            else {
                //Not a valid index number - do nothing
         * Show the sound object
         * @param indexNumber The number of the sound object to be shown
        public void getSound(int indexNumber)
            if(indexNumber < 0){
                //Not a valid index number - do nothing
            else if(indexNumber < playlists.size()){
                //Valid indexNumber
                System.out.println(playlists.get(indexNumber));
            else {
                //Not a valid index number - do nothing
         * @return The number of sounds in the playlist
        public int getSize()
            return playlists.size();
         * List all sounds in the playlist
        public void indexPrintList()
            for(Sound playlist : playlists) {
                playlist.printSound();
         * Lists all sounds in the playlist using an iterator
        public void iteratorPrintList()
            Iterator<Sound> iter = playlists.iterator();
            while(iter.hasNext()) {
                ((Sound)iter.next()).printSound();
         * Gives the total duration of all sounds in the playlist
        *public void totalDuration()*
            *//currently prints all durations - still working on sum*
            *for(Sound playlist : playlists) {*
                *System.out.println(playlist.getDuration());*
         * Plays through all the sounds in the playlist
         * Extra Credit
        public void indexPlayList()
            for(Sound playlist : playlists) {
                playlist.playSound();
         * Plays through all sounds in the playlist using an iterator
         * Extra Credit
        public void iteratorPlayList()
            Iterator<Sound> iter = playlists.iterator();
            while(iter.hasNext()) {
                ((Sound)iter.next()).playSound();
    }

    not sure if I'm missing something here, but this could possibly be solved by initializing a variable to 0 before the for loop, and then adding each duration to this variable as you loop. This seems too trivial a solution though. Again, I may be missing something here.
    something simple like:
    public void calcSum()
        int i = 0;
        for(Fubar foo: fooList) {
            i += foo.getLength();
        System.out.println("Sum = " + i);
    }Edited by: petes1234 on Oct 23, 2007 9:09 AM

Maybe you are looking for

  • Photos no longer sync to iPhone 5s

    Using all latest up to date software iPhone/iTunes/Windows 7 but iTunes is utterly rubbish at sync'ing! I've got a baby to look after than to worry about simple tasks of sync'ing photos of my little one and instead it's a major chore every time with

  • View Settings Resetting

    Ref: Windows 7 Pro SP1 and current version of iTunes I launch itunes; sometimes I get the window that request you acknowleged the use of the software; Then when itunes opens NO memu bar; No view settings So I go to the little window Icon in the upppe

  • Set-Acl permission failed

    I am trying to set the permissions on a folder using the below code, However i get this error :- Cannot find an overload for "FileSystemAccessRule" and the argument count: "6". Functin kozos_Permission($Server) $FolderLocation = "C:\inetpub\ftproo

  • My PC wdoes not load apple store completely when i run diagnosis connecting to itunes store unseccessful

    I can play musci but the itunes store page does not load up. Its says unseccessful when dianostics are run and  that Im not connedcted to internet. I have Windows XP,,

  • It's got to be more than 1.1%

    Are ALL Apple personnel at the launch today? It seems that server P02 and P04, at least, are both down. Why no statement from the company??? All loyal Apple customers are 'cooked'