-2

How do I read filenames from a folder and add them into an arraylist without having to make an array and looping all the answers into the arraylist?

For example, lets say I have a list of txt files in a folder. What do I need to do in order for Java to read through each of the file names and add them into a string array list without having to do a String[] like other answers have suggested?

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Emir
  • 11
  • 3
  • `Files.readAllLines()` is your friend (for reading a single file). – GhostCat Jul 20 '18 at 19:24
  • @GhostCat I think OP wants to read the names of the files in a directory into an `ArrayList`, not the contents. – Jacob G. Jul 20 '18 at 19:25
  • Listing the files in a folder is a bit more work, but again, a solved and well documented problem. – GhostCat Jul 20 '18 at 19:25
  • 1
    It's unclear. My best guess is to use `ArrayList` instead of `String[]` – zlakad Jul 20 '18 at 19:25
  • @JacobG. Hmm, maybe. But still, getting file contents ... is also something that many other answers explain. – GhostCat Jul 20 '18 at 19:26
  • No I don't want the file contents, I just want the names into an ArrayList, I couldn't find any threads on this. – Emir Jul 20 '18 at 19:27
  • @GhostCat I agree, just wanted to update that duplicate, but it's good now. – Jacob G. Jul 20 '18 at 19:27
  • 2
    It seems to me that the linked answers do not provide the answer that the asker was looking for, namely a solution that does not involve writing a loop. I'd use: `Files.list(Paths.get("/path/to/folder")).filter(Files::isRegularFile).collect(Collectors.toList());` – akagixxer Jul 20 '18 at 19:46
  • I agree with @akagixxer - the duplicates are all rather ancient and for modern Java, wrong. – Boris the Spider Jul 20 '18 at 19:47
  • Feel free to put in better answers then! – GhostCat Jul 21 '18 at 06:38
  • @akagixxer You should post that as an answer, since your code does the job the OP is looking for. – MC Emperor Jul 21 '18 at 08:12
  • @MCEmperor sure thing. I think I couldn't earlier because the question was locked, marked as duplicate. – akagixxer Jul 23 '18 at 14:37

2 Answers2

0
File dir = new File(dir);
String[] fileArr  dir.listFiles();
List fileList = Arrays.toList(fileArr); //I bet this is instance of ArrayList

//ArrayList otherFileList = new ArrayList(fileList);
ArrayList otherFileList = new ArrayList();
otherFileList.addAll(fileList);

Note: those are the solutions where YOU don,t write the loop but the loop exists in the other methods.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
monty
  • 7,888
  • 16
  • 63
  • 100
0

If you are using Java 8 or newer you can use the java 'nio' library with java streams to get what you want.

E.g.

final List<Path> files = Files.list(Paths.get("/path/to/folder"))
  .filter(Files::isRegularFile)
  .collect(Collectors.toList());
akagixxer
  • 1,767
  • 3
  • 21
  • 35