0

So I've been having problems trying to collect all the file names inside a specific folder and storing them in an array[] or as commented, a list.

Here's the code so far:

String[] alist = new String[];
Files.list(Paths.get("mypath")).filter(Files::isRegularFile).forEach(System.out::println(alist);

OR

String[] alist;
alist = Files.list(Paths.get("mypath")).filter(Files::isRegularFile).toArray(String[]::new);

OR

Stream<String> alist = Stream.of(Files.list(Paths.get("path")).filter(Files::isRegularFile).toString());
                    String[] alist2 = alist.toArray(size -> new String[size]);

As you can see, I'm have a little trouble figuring out the correct method of doing this.

The purpose being once I've got all the file names stored in an array. I can then split each string in the array. To then create a hashmap [key][name] built from the split strings in the array.

I'm just getting back into java and OOP afters years, so I'm a little rusty.

Thanks for any help!

character
  • 1
  • 1
  • 2
  • Why do you want to use an array? It is more usual to use a `List`. – chrylis -cautiouslyoptimistic- Nov 02 '19 at 23:22
  • I should be using a list you're right. Either/or work as long as it gets the job done. I went ahead and changed the title. – character Nov 02 '19 at 23:23
  • 1
    Java Stream API has some terminal operations e.g `forEach()` and `collect()`. If you need a List just use `Stream.of(...).filter(p->doSomething(p)).collect(Collectors.toList())` As far as I read you really need a HashMap. The `java.util.stream.Collectors` have some useful Collector implementation to create a List or a Map as well. – zforgo Nov 02 '19 at 23:36

2 Answers2

2

As @zforgo said, just use stream.map(for process each element) and collect to get a list result

List<String> filenames = Files.list(Paths.get("D:\\game\\Rayman1"))
    .filter(Files::isRegularFile)
    .map(p -> p.getFileName().toString())
    .collect(Collectors.toList());
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Justin LI
  • 94
  • 3
  • Though not exactly related shouldn't we use try( Stream s = File.list() ) { } source: https://stackoverflow.com/questions/38698182/close-java-8-stream, if used otherwise, may cause open file handles in the os or leak – user2206366 Aug 23 '20 at 20:03
1

Try the following:

    String[] fileNames = Arrays.stream(new File("dir").list().map(File::new)
           .filter(File::isFile).map(File::getName).toArray(String[]::new);

    for (String s : fileNames) {
        System.out.println(s);
    }

Or you can do it like this.

      try {
         String[] fileNames =
               Files.list(Paths.get("dir")).filter(
                     Files::isRegularFile).map(
                           p -> p.toFile().getName()).toArray(String[]::new);

         for (String s : fileNames) {
            System.out.println(s);
         }
      }
      catch (Exception e) {
         e.printStackTrace();
      }
WJS
  • 36,363
  • 4
  • 24
  • 39