@wolf-9830

Как получить список файлов в папке?

Как мне получить список файлов в папке с определенным типом, например .png .jpeg, а так же и под папках?
  • Вопрос задан
  • 4302 просмотра
Пригласить эксперта
Ответы на вопрос 3
zolt85
@zolt85
Программист
Подпапки обходить рекурсивно. Список файлов можно получить при помощи метода listFiles , в который можно передать FilenameFilter
Ответ написан
Комментировать
EugeneP2
@EugeneP2
Java Dev
Можно воспользоватся готовым. Есть серия библиотек от апач с кучей готовых решений, вот одна из них
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>


import java.io.File;
import java.util.Collection;

import org.apache.commons.io.FileUtils;

public class Test {

	public static void main(String[] args) {
		Collection<File> files = FileUtils.listFiles(new File("/home/user/workspace"), new String[] {"java"}, true);
		
		for (File file : files) {
			System.out.println(file);
		}
	}
}
Ответ написан
Комментировать
@odissey_nemo
Программист, ГИС-системы, растры, космоснимки
Вот текст статической подпрограммы из собственного класса Files (часто встречающиеся операции с файлами, сбор имён не требовался ), стирающей всё содержимое заданной директории. В т.ч. и рекурсивно (по параметру). Для чего требуется стереть все файлы и во всех вложенных директориях.Переработать в нужном направлении нетрудно, добавив параметр для сбора имён обнаруженных файлов и его заполнение в нужном формате:
/**
	 * Tries to remove all files (and sub-directories optionally) in the designated
	 * directory
	 *
	 * @param dir_path  directory path to clear from other files and optionally
	 *                  directories
	 * @param recursive deletes sub-dirs also if set to {@code true}
	 * @return {@code true} if operation completed successfully that is no errors
	 *         occurs during operation, else {@code false}
	 */
	public static boolean clearDirectory( String dir_path, boolean recursive )
	{
		File dir = new File( dir_path );
		if ( !dir.isDirectory() )
		{
			return false;
		}
		boolean res = true;
		String[] files = dir.list();
		String fdir = Files.resetDir( dir_path );
		String fpath;
		StringBuffer sb = new StringBuffer();
		for ( int i = 0; i < files.length; i++ )
		{
			sb.delete( 0, Integer.MAX_VALUE ).append( fdir ).append( files[ i ] );
			File file = new File( fpath = sb.toString() );
			if ( file.isDirectory() && recursive )
			{
				res = clearDirectory( fpath, recursive );
			}
			else
			{
				try
				{
					res = file.delete();  // TODO: здесь забирать конкретное имя фала в общий выходной массив
				}
				catch ( SecurityException se )
				{
				}
			}
		}
		return res;
	}


Вызываемый дополнительно код ниже:

/**
	 * The system-dependent default name-separator character. This field is
	 * initialised to contain the first character of the value of the system
	 * property file.separator. On UNIX systems the value of this field is '/'; on
	 * Microsoft Windows systems it is '\\'.
	 */
	public static final char FileSeparator = File.separatorChar;

	/**
	 * The system-dependent default name-separator character. This field is
	 * initialised to contain the first character of the value of the system
	 * property file.separator. On UNIX systems the value of this field is '/'; on
	 * Microsoft Windows systems it is '\\'.
	 */
	public static final char FS = File.separatorChar;

	/**
	 * appends system dependent file separator char
	 *
	 * @param FilePath - string to check for file separator existence
	 * @return new string with appended file separator or the same string if it
	 *         already was present
	 */
	public static String appendFileSeparator( String FilePath )
	{
		return appendFileSeparator( FilePath, FileSeparator );
	}

	/**
	 * appends system dependent file separator char
	 *
	 * @param FilePath - string to check for file separator existence
	 * @param sep      character to be a last separator in the input string
	 * @return new string with appended file separator or the same string if it
	 *         already was present
	 */
	public static String appendFileSeparator( String FilePath, char sep )
	{
		if ( Text.isEmpty( FilePath ) )
		{
			return "" + sep;
		}
		char ch = FilePath.charAt( FilePath.length() - 1 );// get last symbol
		if ( ( ch != '/' ) && ( ch != '\\' ) )// check it to be a separator one
		{
			return FilePath + sep;
		}
		else
		{
			return FilePath.substring( 0, FilePath.length() - 1 ) + sep;
		}
	}


	/**
	 * the same as {@link #appendFileSeparator} but with shorter name :o)
	 *
	 * @param path path to append file separator
	 * @return path with trailing current file names separator
	 */
	public static String resetDir( String path )
	{
		if ( path == null )
		{
			return null;
		}
		return appendFileSeparator( path );
	}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽