Java – sort an array of file names containing numeric strings
For my project, I need to download a zip file from the FTP server. I can publish a new zip about 13 times a year I need to download the latest file according to the naming convention of the server:
For example: alfp1016f zip
The prefix will always be the same (alfp) and the suffix is f or P (for "full" or "partial"; I only need files ending with F) In addition, there are several other files in the directory that need to be ignored because they have different prefixes Then, I need to get the latest files in the array according to this priority:
>Last year Of course '99 should not be regarded as the latest year. > Latest version number
For example, if I have this file name list (full server directory):
1stpage712.pdf 1stpage914.pdf ALFP1015F.zip ALFP1015P.zip ALFP716F.zip ALFP716P.zip FSFP816F.zip FSFP816P.zip
My expected output is alfp716f Zip, because 16 is the latest year and 7 is the version number of the latest year
.
This is what I have done so far:
//necessary imports import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; //initialize FTP client ftpClient = new FTPClient(); try { //connect to server ftpClient.connect(server,port); ftpClient.login(username,password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //list all names from server String[]filenames = ftpClient.listNames(); //return expected file name String expectedFileName = returnMostRecent(filenames); } catch (Exception e) { e.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); System.out.println("Disconnected from server"); } } catch (IOException ex) { ex.printStackTrace(); } }
I wrote the returnmostrecent (string []) method. I made a tragic attempt, but in the end, there was an incredible garbled code, which is not worth posting here
How do I sort this array and effectively return the most recent files in my order of priority?
Solution
I haven't tested it, but I think it should work
private String returnMostRecent(String[] fileNames) { String file = null; double version = -1; for(String name : listNames) { // skip files that don't match if (!name.matches("ALFP[0-9]*F.zip")) continue; // get digits only String digits = name.replaceAll("\\D+",""); // format digits to <year>.<version> String vstr = digits.substring(digits.length-2,digits.length()) + "."; if (digits.length() < 4) vstr += "0"; vstr = digits.substring(0,digits.length()-2); double v = Double.parseDouble(vstr); if (v > version) { version = v; file = name; } } return file; }