Marenthyu Marenthyu - 1 month ago 7
Java Question

Got a Version list as Folders, want to find highest Version

So, i have this List of Folders which represent the Versions of a Program and i want to get the latest (there are some junk files next to the Folders!):

0.0.0.256
0.0.1.1
0.0.1.2
0.0.1.5
0.0.1.11
0.0.1.68
0.0.2.1


and so on.

If i want to get only the latest Version Folder here, how could i accomplish that?

Currently, i know that the version wont rise higher than 0.0.1.x for now, (the above is only an example) so i could use

for(String name:names)
{

if (name.indexOf("0.0.1")==0)
{


ret = name;
}
}
System.out.println("Current Installed Version Folder: "+ret);


but that wont last forever. How could i write some code, that will always give me the highest representive Version number? I can think of a way how to do it right now (checking the 0th char, then the 2nd, 4th and so on) but i think there is a smarter way. Any quick ideas?

Answer

The idea would be to use a comparator to compare each String (I removed the part which was using the Set) :

public static void main(String [] args){
    String [] names = { "0.0.1.1",
                        "1.0.1.1",
                        "0.0.1.2",
                        "0.0.1.5",
                        "0.0.1.11",
                        "0.0.0.100",
                        "0.0.0.256",
                        "0.0.2.1",
                        "0.0.1.68"};
    String maxVersion = names[0];

    for(int i = 1; i < names.length; i++){
        if(compare(maxVersion, names[i]) == 1)
            maxVersion = names[i];
    }
    System.out.print(maxVersion);
}
static int compare(String a, String b){
     String[] sA = a.split("\\.");
     String[] sB = b.split("\\.");
     for(int i = 0; i < sA.length; i++){
        int cmp = Integer.compare(Integer.parseInt(sB[i]), Integer.parseInt(sA[i]));
        if(cmp != 0)
            return cmp;
     }
    return 0;
}

Which outputs:

"1.0.1.1"

Note that this assume that each version number has the same length, but you can change this by checking both the length of the resulting arrays when splitting.


i got another problem: i got some files next to the Version Folders, so i can't get the names List from File.list()

You can provide a FileNameFilter with the listFiles method:

File file = new File("/pathToVersionFolders");
File[] files = file.listFiles(new FilenameFilter() {
  @Override
  public boolean accept(File dir, String name) {
      return new File(dir, name).isDirectory();
  }
});

Now you have only the directories. If you want to get only the names, you can use list.

Comments