Поток никак не хочет закрываться и не могу понять в чем причина. Я использовал try-with-resources как советуют здесь
https://javarush.com/help/11873 но это не помогает.
может проблема в стриме Files.readAllLines() который внутри у себя использует баферридер. Но я его не могу закрыть напрямую.
Да и вроде он должен по дефолту закрывается, ведь так? Разработчики должны былои продумать этото момент.
вот метод readAllLines из класса Files>
public static List<String> readAllLines(Path path, Charset cs) throws IOException {
try (BufferedReader reader = newBufferedReader(path, cs)) {
List<String> result = new ArrayList<>();
for (;;) {
String line = reader.readLine();
if (line == null)
break;
result.add(line);
}
return result;
}
}package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.OptionalInt;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) throws IOException {
// args = new String[]{"-u", "198479" , " aaaaaaaaaaaaaaaaa", "23.00", "44"};
if (args.length != 0) {
String fileName = null;
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){;
fileName = br.readLine();}
//String idC = args[0];
switch (args[0]) {
case "-u":
String id = args[1];
Integer idInt = Integer.parseInt(id);
String podName = args[2];
podName = podName.length() > 30 ? podName.substring(0, 30) : podName;
String price = args[3];
price = price.length() > 8 ? price.substring(0, 8) : price;
String quantity = args[4];
quantity = quantity.length() > 4 ? quantity.substring(0, 4) : quantity;
String newStr = String.format("%-8s%-30s%-8s%-4s", id, podName, price, quantity);
// System.out.println(newStr);
List<String> allLines = Files.readAllLines(Paths.get(fileName));
List<String> listNEw = allLines.stream().filter(lines -> !lines.isEmpty())
.map(lines2 ->
lines2.substring(0, 8).trim().equals(id) ?
lines2.replaceAll(lines2, newStr) : lines2).collect(Collectors.toList());
try (FileWriter file = new FileWriter(fileName)) {
try (BufferedWriter writer = new BufferedWriter(file)) {
for (String s : listNEw) {
writer.write(s);
writer.newLine();
}
}
}
break;
case "-d":
String id2 = args[1];
List<String> allLines2 = Files.readAllLines(Paths.get(fileName));
//IF CHECK
String line = allLines2.stream()
.filter(p -> p.substring(0, 8).trim().equals(id2))
.findFirst()
.get();
allLines2.remove(line);
try (FileWriter file2 = new FileWriter(fileName)) {
try (BufferedWriter writer2 = new BufferedWriter(file2)) {
for (String s : allLines2) {
writer2.write(s);
writer2.newLine();
}
}
}
break;
}
}
}
}