Home > OS >  Sonar scan says Use try-with-resources or close this "Stream" in a "finally" cla
Sonar scan says Use try-with-resources or close this "Stream" in a "finally" cla

Time:02-23

Sonar qube is giving me the following error. Use try-with-resources or close this "Stream" in a "finally" clause. this is my code.

Path start = Paths.get(filePath);
Stream<File> stream;
try {
    stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS).map(s -> s.toFile());
    List<File> files = stream.collect(Collectors.toList());
                    files.remove(0);
                    for (File f : files) {
                        String fileName = f.toPath().getFileName().toString();
                        if (fileName.matches(regex)) {
                            fileList.add(f.toPath().toString());
                        }
                    }
    } catch (IOException e) {
}

How can I fixed this error. Thanks in Advanced!!

CodePudding user response:

define and open your stream this way:

try (Stream<File> stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS).map(s -> s.toFile())){

Doing this, the system will automatically close the stream and you don't need to worry about it

CodePudding user response:

Expanding from what Ryan said, I prefer to keep the scope of the stream that's to be closed as small as possible:

try (Stream<File> stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS)) {
    List<File> files = stream
            .map(s -> s.toFile())
            .collect(Collectors.toList());
}

That said, you stream, collect to a list, then loop some more. That can be improved:

try (Stream<File> stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS)) {
    stream
            .skip(1) // replacement of files.remove(0)
            // leave out converting to File
            .filter(f -> f.getFileName().toString().matches(regex)) // filter in the stream
            .map(Path::toString)
            .forEach(fileList::add);
}

I don't really like that fileList::add, so if you can collect to a List<String> and assign that to fileList that would be preferred. Or perhaps collect to a List<String> and then use fileList.addAll.

CodePudding user response:

Close the stream in case it will throw an exception while the stream is opened.

  public static void main(String[] args) {
    Path start = Paths.get("");
    Stream<File> stream = null;
    List<String> fileList = new ArrayList<>();
    try {
        stream = Files.walk(start, 1, FileVisitOption.FOLLOW_LINKS).map(s -> s.toFile());
        List<File> files = stream.collect(Collectors.toList());
        files.remove(0);
        for (File f : files) {
            String fileName = f.toPath().getFileName().toString();
            if (fileName.matches("")) {
                fileList.add(f.toPath().toString());
            }
        }
    } catch (IOException e) {
    // Do something
    }finally {
        if(stream!=null)
            stream.close();
    }
}
  • Related