Tengo un método que obtiene los nombres de los ficheros de un directorio, ordenados alfabéticamente, por ejemplo así:
aaa.txt
abb.rar
bbb.txt
x.bmp
xa.as
zz.bmp
Quiero poder ordenarlos primero por tipo de archivo (alfabéticamente ) y luego dentro de cada grupo alfabéticamente por nombre, es decir:
xa.as
x.bmp
zz.bmp
abb.rar
aaa.txt
bbb.txt
Mí código de partida:
public String[] getNames( String path ) {
String[] arr_res = null;
File directory = new File( path );
File[] arr_content = directory.listFiles();
int len = arr_content.length;
List<String> res = new ArrayList<>();
for ( int i = 0; i < len; i ++ ) {
if ( arr_content[ i ].isFile( ))
res.add( arr_content[ i ].getName( ));
}
if ( res.size() > 0 )
arr_res = res.toArray( new String[ 0 ] );
return arr_res;
}
Se me ha ocurrido extraer las extensiones de los ficheros, hacer grupos ordenados para cada una de estas y luego componer la salida. Quisiera saber si conocen alguna forma más simple y directa. Aporto mi solución con la que se pueden obtener, indistintamente, las dos listas de ficheros anteriores (perdonar por el código extra que permite obtener listado de los directorios):
import java.util.ArrayList;
import java.util.List;
public class Strings {
private static List<String> res = new ArrayList<>();
/**
* Cleans the array of empty strings
*
*/
public static String[] delEmpties( String[] arr ) {
res.clear();
int len = arr.length;
for ( int i = 0 ; i < len; i ++ ) {
if ( ! arr[ i ].equals( "" ))
res.add( arr[ i ] );
}
return res.toArray( new String[ 0 ] );
}
/**
* Filters the array of strings and delete repeat elements
*
*/
public static String[] filterRepeated( String[] arr ) {
int len = arr.length;
for ( int i = 0 ; i < len; i ++ ) {
for ( int j = 0; j < ( len - 1 ); j ++ ) {
if ( i != j ) {
if ( arr[ i ].equals( arr[ j ] )) {
arr[ j ] = ""; //replace value by empty string
}
}
}
}
return delEmpties( arr );
}
} //class
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
public class ContentFilter {
private static List<String> res = new ArrayList<>();
private static String[] arr_res = null;
/**
* Gets the directories from the directory content
*
* @param String The directory path
* @return String[]
*/
public static String[] getDirectoryNames( String path ) {
return getNames( path, "directories" );
}
/**
* Gets the files from the directory content
*
*/
public static String[] getFileNames( String path ) {
return getNames( path, "files" );
}
/**
* Gets the files from the directory content
*
*/
public static String[] getFileNames(
String path,
boolean order_by_type
) {
return ( order_by_type )
? getNamesByType( path )
: getNames( path, "files" );
}
/**
* Gets the file types from array of file names
*
*/
public static String[] getFileTypes( String[] names ) {
if ( names != null ) {
int size = names.length;
String file_type = "";
res.clear(); //remove previous content
for ( int i = 0; i < size; i ++ ) {
file_type = getFileType( names[ i ] );
res.add( file_type );
}
if ( res.size() > 0 ) {
arr_res = res.toArray( new String[ 0 ] );
Arrays.sort( arr_res );
arr_res = Strings.filterRepeated( arr_res );
}
}
return arr_res;
}
/**
* Gets the names for files / directories
*
*/
public static String[] getNames( String path, String type ) {
File directory = new File( path );
File[] arr_content = directory.listFiles();
if ( arr_content != null ) {
int len = arr_content.length;
res.clear(); //remove previous content
for ( int i = 0; i < len; i ++ ) {
if ( type.equals( "directories" ) && arr_content[ i ].isDirectory( ))
res.add( arr_content[ i ].getName( ));
if ( type.equals( "files" ) && arr_content[ i ].isFile( ))
res.add( arr_content[ i ].getName( ));
}
if ( res.size() > 0 )
arr_res = res.toArray( new String[ 0 ] );
} else
System.err.println( "Err -> Sin contenido de \"" + path + "\"" );
return arr_res;
}
/**
* Gets the file types
*
*/
public static String[] getNamesByType( String path ) {
String[] file_names = getNames( path, "files" );
String[] file_types = getFileTypes( file_names );
if ( file_types != null ) {
//Groups file names by file extension
Hashtable<String, String[]> groups = getGroups(
file_names,
file_types
);
arr_res = getArrayFromGroups( groups );
}
return arr_res;
}
/**
* Aux. getFileTypes()
* Gets file type from a file name
*
*/
private static String getFileType( String name ) {
int pos;
String type = name;
while (( pos = type.indexOf( "." )) > -1 ) {
type = name.substring(
pos + ".".length(),
name.length()
);
}
return type;
}
/**
* Groups file names by file extension
*
*/
private static Hashtable<String, String[]> getGroups(
String[] file_names,
String[] file_types
) {
int size_file_names = file_names.length;
int size_file_types = file_types.length;
String file_name, file_type;
Hashtable<String, String[]> groups = new Hashtable<>();
//groups.put( "Ciudades España", new String[] { "Madrid", "Teruel" } );
//Iterates over file extensions
for ( int i = 0; i < size_file_types; i ++ ) {
res.clear();
file_type = file_types[ i ];
//Iterates over file names
for ( int j = 0; j < size_file_names; j ++ ) {
file_name = file_names[ j ];
//Finded file extension inside the file name
if ( file_name.indexOf( file_type ) > -1 ) {
res.add( file_name );
}
}
groups.put(
file_type,
res.toArray( new String[ 0 ] ) //String[] with file names of one type
);
}
return groups;
}
private static String[] getArrayFromGroups(
Hashtable<String, String[]> groups
) {
res.clear();
String[] keys = getKeys( groups ); //Gets the keys
int keys_size = keys.length;
for ( int i = 0; i < keys_size; i ++ ) {
String key = keys[ i ];
String[] temp_arr = groups.get( key );
for ( String str : temp_arr ) {
res.add( str );
}
}
arr_res = res.toArray( new String[ 0 ] );
return arr_res;
}
/**
* Aux. getArrayFromGroups()
*
*/
private static String[] getKeys(
Hashtable<String, String[]> groups
) {
Enumeration<String> e = groups.keys();
List<String> temp = Collections.list( e );
String[] keys = temp.toArray( new String[ 0 ] );
Arrays.sort( keys );
return keys;
}
} //class
Clase para trazado:
public class Trace {
/**
* Prints the strings stored into an array
*
*/
public static void strArray( String[] arr_strs, String msg ) {
System.out.println( "Trace / strArray()" );
System.out.println( msg );
if ( arr_strs != null ) {
int len = arr_strs.length;
String str;
for ( int i = 0; i < len; i ++ ) {
str = arr_strs[ i ];
System.out.println( str );
}
} else
System.err.println( "Trace / strArray() -> Err: recibido \"null\"" );
System.out.println( "-------------------------" );
}
} //class
Clase con los test:
import app.helpers.ContentFilter;
import app.helpers.Strings;
import app.helpers.Trace;
import java.util.Arrays;
class Test {
static String path = "d://_test/";
public static void main( String[] args ) {
String[] arr1 = ContentFilter.getFileNames( path );
String[] arr2 = ContentFilter.getFileNames( path, true );
Trace.strArray( arr1 );
Trace.strArray( arr2 );
}
} //class