Java: Find.archivos txt en la carpeta especificada [cerrado]
¿Hay un código Java incorporado que analizará una carpeta dada y buscará archivos .txt
?
8 answers
Puede usar el método listFiles()
proporcionado por la clase java.io.File
.
import java.io.File;
import java.io.FilenameFilter;
public class Filter {
public File[] finder( String dirName){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".txt"); }
} );
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-04 22:16:11
Intenta:
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getName());
}
}
return textFiles;
}
Desea hacer una búsqueda que no distingue entre mayúsculas y minúsculas, en cuyo caso:
if (file.getName().toLowerCase().endsWith((".txt"))) {
Si desea buscar recursivamente a través de un árbol de directorios archivos de texto, debería ser capaz de adaptar lo anterior como una función recursiva o una función iterativa utilizando una pila.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-06 05:43:38
import org.apache.commons.io.filefilter.WildcardFileFilter;
.........
.........
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
El código anterior funciona muy bien para mí
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-23 13:30:15
Es realmente útil, lo usé con un ligero cambio:
filename=directory.list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.startsWith(ipro);
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-08 15:27:07
Hice mi solución basada en las publicaciones que encontré aquí con Google. Y pensé que no hay daño para publicar el mío también, incluso si es un hilo viejo.
La única ventaja de este código es que también puede iterar a través de subdirectorios.
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
El método es el siguiente:
List <File> exploreThis(String dirPath){
File topDir = new File(dirPath);
List<File> directories = new ArrayList<>();
directories.add(topDir);
List<File> textFiles = new ArrayList<>();
List<String> filterWildcards = new ArrayList<>();
filterWildcards.add("*.txt");
filterWildcards.add("*.doc");
FileFilter typeFilter = new WildcardFileFilter(filterWildcards);
while (directories.isEmpty() == false)
{
List<File> subDirectories = new ArrayList();
for(File f : directories)
{
subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
}
directories.clear();
directories.addAll(subDirectories);
}
return textFiles;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 09:17:42
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
public class FileFinder extends SimpleFileVisitor<Path> {
private PathMatcher matcher;
public ArrayList<Path> foundPaths = new ArrayList<>();
public FileFinder(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path name = file.getFileName();
if (matcher.matches(name)) {
foundPaths.add(file);
}
return FileVisitResult.CONTINUE;
}
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
Path fileDir = Paths.get("files");
FileFinder finder = new FileFinder("*.txt");
Files.walkFileTree(fileDir, finder);
ArrayList<Path> foundFiles = finder.foundPaths;
if (foundFiles.size() > 0) {
for (Path path : foundFiles) {
System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
}
} else {
System.out.println("No files were founds!");
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-26 21:28:47
Aquí está mi código específico de plataforma (unix)
public static List<File> findFiles(String dir, String... names)
{
LinkedList<String> command = new LinkedList<String>();
command.add("/usr/bin/find");
command.add(dir);
List<File> result = new LinkedList<File>();
if (names.length > 1)
{
List<String> newNames = new LinkedList<String>(Arrays.asList(names));
String first = newNames.remove(0);
command.add("-name");
command.add(first);
for (String newName : newNames)
{
command.add("-or");
command.add("-name");
command.add(newName);
}
}
else if (names.length > 0)
{
command.add("-name");
command.add(names[0]);
}
try
{
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
p.waitFor();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
// System.err.println(line);
result.add(new File(line));
}
p.destroy();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-06 06:01:31
Import org.apache.commons.io.FileUtils;
List htmFileList = new ArrayList ();
For (File file: (List) FileUtils.listFiles (new File (srcDir), new String [] {"txt", " TXT"}, verdadero)) { htmFileList.add (archivo);}
Este es mi último código para agregar todos los archivos de texto de un directorio
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-25 13:09:52