-1

I need to search a folder in Java and get all the names of .txt files in the folder into an ArrayList.. I got NO idea what so ever how to do this.. :) So I would be glad to receive any help and ideas that you guys have :)

And just to specify.. its not the .txt I want to load.. just the names from the .txt files. and there is only txt documents in the folder by the way. :)

I wonder if there is anything like

for(games/ get all txt documents){ArrayList add.nameOfTxt};
MariuszS
  • 30,646
  • 12
  • 114
  • 155
HOervald
  • 25
  • 1
  • 7
  • 1
    Look at the `File` methods with 'list' in the name. For filtering for txt, look into [`FileFilter`](http://docs.oracle.com/javase/7/docs/api/javax/swing/filechooser/FileFilter.html).. – Andrew Thompson Jan 11 '14 at 15:27

1 Answers1

0

All needed information are on stack already, use search :)

Sample code

public static void main(String[] args) throws IOException {
    String suffix = ".xml";
    File directory = new File(".");

    List<File> files = listFilesWithSuffix(directory, suffix);

    List<String> fileNames = convertFilesToNames(files);

    for (String fileName : fileNames) {
        System.out.println(fileName.substring(0, fileName.length() - suffix.length()));
    }
}

private static List<File> listFilesWithSuffix(File directory, final String suffix) {
    File[] files = directory.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(suffix);
        }
    });
    return Arrays.asList(files);
}

private static List<String> convertFilesToNames(List<File> files) {
    List<String> fileNames = new ArrayList<String>();
    for (File file : files) {
        fileNames.add(file.getName());
    }
    return fileNames;
}
Community
  • 1
  • 1
MariuszS
  • 30,646
  • 12
  • 114
  • 155