Ramiro Arizpe Ramiro Arizpe - 1 month ago 13
Java Question

Using Collections on Java, Apache FileItem sort()

How can I sort a FileItem list?

I have the next code:

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);


This list always can have 2 files (one PDF and one XML, the files name are the same, only the extension change). I need the items first come the pdf then the XML, but the default way Windows sort the files are by Name, if this sort change, the items can be XML then PDF.

Example:

If the sort of Windows it's by name, the items should come's like this:

enter image description here

//The expected sort
items.get(0).getName(); //This should be equals: PAX147896.pdf
items.get(1).getName(); //This should be equals: PAX147896.xml


But if I sort for other thing like this:

enter image description here

//The unexpected sort
items.get(0).getName(); // PAX147896.xml
items.get(1).getName(); // PAX147896.pdf


Can someone give me an example of items.sort() method, I know I need a Collection but I really don't know how to use it....

Any help will be really grateful.

Answer

Well, it's not a dynamically fix, but it can be done like this:

private List<FileItem> orderFileItems(List<FileItem> items){
    FileItem fileXML = null; // index 1
    FileItem filePDF = null; // index 0
    if(items.get(0).getName().endsWith("xml") && items.get(1).getName().endsWith("pdf")){
        fileXML = items.get(0);
        filePDF = items.get(1);
        items.set(0, filePDF);
        items.set(1, fileXML);
    }        
    return items;
}

But still don't know how to use a Collection...

Comments