0

Нужна ваша помощь. Класс FileReader формирует стрим из лог-файла:

public class FileReader {

    public Stream<String> readFile(String fileName) throws FileNotFoundException {
        URL fileURL = this.getClass().getClassLoader().getResource(fileName);
        try {
            if (fileURL == null) {
                throw new FileNotFoundException("Missing file \"" + fileName + "\"");
            }
            return Files.lines(Paths.get(fileURL.toURI()));
        } catch (IOException | URISyntaxException exception) {
            throw new FileNotFoundException("Missing file \"" + fileName + "\"");
        }
    }
    
}

Подскажите пожалуйста, как здесь применить конструкцию try-with-resources? Так не работает, поскольку URL не реализует java.lang.AutoCloseable:

try (URL fileURL = this.getClass().getClassLoader().getResource(fileName)) { ...
2
  • А не реализует URL интерфейс AutoCloseable потому, что ничего не открывает и закрывать соответственно нечего. 3 янв 2022 в 10:23
  • Сперва определитесь зачем вам это нужно? Что вы хотите сделать? 3 янв 2022 в 11:15

1 ответ 1

1

Со стримами try-with-resources надо применять там, где с ними идёт работа. В вашем случае в месте вызова метода readFile:

try (Stream<String> stream = fileReader.readFile("some_file.txt")) {
    stream.forEach(System.out::println);
}
1
  • Спасибо за помощь!
    – AlexCoder
    3 янв 2022 в 11:56

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.