-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};
1
  • 1
    Look at the File methods with 'list' in the name. For filtering for txt, look into FileFilter.. Commented Jan 11, 2014 at 15:27

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.