1

I am using Files.walk function to get the files present in a sub directory of a main directory. for example :

/path/to/stuff/foo/bar1/myfile.sql
/path/to/stuff/foo/bar1/myfiles.sql
/path/to/stuff/foo/bar2/myfile.sql
/path/to/stuff/foo/bar3/myfile.sql
/path/to/stuff/foo/bar4/myfile.sql
/path/to/stuff/foo/bar5/
/path/to/stuff/foo/bar6/myfile.sql
/path/to/stuff/foo/bar7/myfile.sql
/path/to/stuff/foo/bar8/myfile.sql
/path/to/stuff/foo/bar9/myfile.sql

this is my code :

Files.walk(Paths.get("/path/to/stuff")).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                buildFiles();
            }
            });

in the buildFiles i need to get the filename and the subfoldername and make that as a file name example loop 1 : path=/path/to/stuff/foo/bar1/myfile.sql and the filename should be foo_bar1.sql. How would i do that?

Sushin K.Kumar
  • 149
  • 1
  • 3
  • 12

1 Answers1

0

you have to create a file using the path. That will help you to manage your file. I guess you wonder if creating a file with

new file()

won't overwrite your file. Don't worry it won't It will help to have some sort of java reference to your file.

    Files.walk(Paths.get("/path/to/stuff")).forEach(filePath -> {
                     if (Files.isRegularFile(filePath1)) {
                     File file1 = new File(filePath1);
                     String folderName = file.getName();
                     Files.walk(Paths.get("/path/to/stuff"+folderName)).forEach(filePath2 -> {
                           if (Files.isRegularFile(filePath2)) {
                           File file2 = new File(filePath2);
                           String subFolderName = file2.getName();
                           String result = folderName+subFolderName+".sql";
                           builFiles(result)
                          }
                     });
                  }
               });
Vivien SA'A
  • 727
  • 8
  • 16
  • This wont work. I need the file name to be `foo_bar1.sql` from one the path : `/path/to/stuff/foo/bar1/myfile.sql` The function `buildFiles()` was precisely for that reason but i was not able to come up with a easy logic. – Sushin K.Kumar Jan 30 '17 at 10:42
  • Is there any way to get the last two subfolder names. – Sushin K.Kumar Jan 30 '17 at 10:43
  • Ok I can see what you desire. I think you can get the first folder then you keep it name in a variable, after that, you search that folder and you catch the element(folder) that it contains and get it name, that you concatenate with the first folder name and you add the extention .sql. Actually try to look my answer I've just edited it I hope I've now understood what you mean – Vivien SA'A Jan 30 '17 at 13:20