Search code examples
javafilepathsimplify

Can I simplify this solution?


I want to simplify my code.

my code is for listing directories , check if folders contain files : strings.xml and if specific folder contais file , split names of these folders to get language suffix (load it to table or list), example : my directories tree contains a few folders
--value
--value-en
--value-de
--value-pl
--other folders

my code : languages is a [] in below example

Path dir_path = Paths.get("D:/Work/Projekty/Java/Tools/Mobilne zasoby/arcadia-drafter/res/");
	DirectoryStream<Path> stream = Files.newDirectoryStream(dir_path);
	for (Path file_path : stream) 
   {
		DirectoryStream<Path> stream1 = Files.newDirectoryStream(file_path, "strings.xml");
		for (Path xml_name : stream1) 
     {
			if (file_path.getFileName().toString().startsWith("values-")) 
       {
				languages = file_path.getFileName().toString().split("-"); 
			}
		}
}

Can you please help me simplify this code ? I wonder if i have to 2 times use Directory stream.


Solution

  • I'm not sure if the code you provide solves the problem you described. But assuming it does - there are couple of suggestions:

    • DirectoryStream should be closed. If you are not using a try-with-resources statement, don't forget to close the stream in the finally block.
    • Also, to make code readable - I would suggest to split this method in several simpler methods each with single responsibility.

    So, here is one possible approach to make code in a way cleaner:

    public List<String> getLanguages(String directoryPath) throws IOException {
      List<String> languages = new ArrayList<>();
      try (DirectoryStream<Path> paths = Files.newDirectoryStream(Paths.get(directoryPath))) {
        for (Path filePath : paths) {
          try (DirectoryStream<Path> filePaths = Files.newDirectoryStream(filePath, "strings.xml")) {
            languages.addAll(getValues(filePaths));
          }
        }
      }
      return languages;
    }
    
    private List<String> getValues(DirectoryStream<Path> paths) {
      return StreamSupport.stream(paths.spliterator(), false)
          .map(path -> path.getFileName().toString())
          .filter(fileName -> fileName.startsWith("values-"))
          .flatMap(fileName -> Arrays.stream(fileName.split("-")))
          .collect(Collectors.toList());
    }