Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save slgithub/fd5de3ddf31e7884c971 to your computer and use it in GitHub Desktop.
Save slgithub/fd5de3ddf31e7884c971 to your computer and use it in GitHub Desktop.
Sorting files 'numerically' instead of alphabetically in java
System.out.println("pathFolderPath IN RUN :::::" + pathFolderPath);
	File[] fileList = null;

	File folder = new File(pathFolderPath);
	
	if (folder.isDirectory()) {

		// Creating a filter to return only files.
		FileFilter fileFilter = new FileFilter() {
			public boolean accept(File file) {
				return !file.isDirectory();
			}
		};

		fileList = folder.listFiles(fileFilter);

		// Sort files by name
		Arrays.sort(fileList, new Comparator<File>() {
		    public int compare(File f1, File f2) {
		        try {
		        	String fName1=f1.getName().substring(0,f1.getName().lastIndexOf("."));
		        	String fName2=f2.getName().substring(0,f2.getName().lastIndexOf("."));
		        	/*System.out.println(fName1);
		        	System.out.println(fName2);*/
		        	
		            int i1 = Integer.parseInt(fName1);
		            int i2 = Integer.parseInt(fName2);
		            return i1 - i2;
		        } catch(NumberFormatException e) {
		            throw new AssertionError(e);
		        }
		    }
		});

		for (File f : fileList) {
			System.out.println("File:" + f.getName());
			
		}

	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment