The Artima Developer Community
Sponsored Link

Java Buzz Forum
Howto Sort Files and Directories

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Janek Schwarz

Posts: 95
Nickname: jschwarz
Registered: Nov, 2004

Janek Schwarz is a software developer specialized in client-side Java technologies
Howto Sort Files and Directories Posted: Jan 16, 2005 3:18 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Janek Schwarz.
Original Post: Howto Sort Files and Directories
Feed Title: The Wannabe Java Rockstar
Feed URL: http://weblog.janek.org/Archive/Categories/javablogs.rss.xml
Feed Description: The Wannabe Java Rockstar: Janek's weblog where all posts go to Eleven
Latest Java Buzz Posts
Latest Java Buzz Posts by Janek Schwarz
Latest Posts From The Wannabe Java Rockstar

Advertisement

Via Technorati's new tag feature I found a quick and dirty algorithm for sorting files and directories. The author asked for improved versions. Here's mine:

import java.io.File;
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;

public class FileSort
{
public static void main(String[] args)
{
 
File dir = new File("D:/home/schwarz/Eigene Dateien");
  File
[] selectedFiles = dir.listFiles();

 
for(int i = 0; i < selectedFiles.length; i++)
   
System.err.println(selectedFiles[i]);

  Arrays.sort
(selectedFiles, new FileComparator());

 
for(int i = 0; i < selectedFiles.length; i++)
   
System.err.println(selectedFiles[i]);
}

private static class FileComparator
 
implements Comparator
{
private Collator c = Collator.getInstance();

public int compare(Object o1,
                   Object o2
)
{
 
if(o1 == o2)
   
return 0;

  File f1 =
(File) o1;
  File f2 =
(File) o2;

 
if(f1.isDirectory() && f2.isFile())
   
return -1;
 
if(f1.isFile() && f2.isDirectory())
   
return 1;

 
return c.compare(f1.getName(), f2.getName());
}
}
}

Read: Howto Sort Files and Directories

Topic: Futures 3: Transparent Futures in Java Previous Topic   Next Topic Topic: Hiring Techies, Project Management

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use