Чтение/Запись в файл

Необходимо считать данные с файла input.txt, отфильтровать сотрудников по должности. Результат записать в файл output.txt.

Написал метод getAllEmployee() который считывает данные из файла, а также метод который фильтрует сотрудников по должности filter(). Но не знаю как записать результат фильтрации в файл output.txt. Подскажите пожалуйста.

/*
Конструктор класса Employee.
public Employee(int id, String fullName, String position, int hireDate) {
        this.id = id;
        this.fullName = fullName;
        this.position = position;
        this.hireDate = hireDate;
    }
*/
 
public class EmployeeCollection {
    private static final Scanner scanner = new Scanner(System.in);
    private static List<Employee> employeeList;

    public static List<Employee> getAllEmployee() {
        File file = new File("src/input.txt");
        employeeList = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = reader.readLine();
            while (line != null) {
                String[] personList = line.split(" ");
                employeeList.add(new Employee(Integer.parseInt(personList[0]), personList[1], personList[2], Integer.parseInt(personList[3])));
                line = reader.readLine();
            }
        } catch (NumberFormatException e) {
            System.out.println("Неверные параметры");
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return employeeList;
    }


    public static List<Employee> filter() {
        List<Employee> out;
        out = getAllEmployee();

        System.out.print("Введите должность сотрудника: ");
        String position = scanner.nextLine();
        System.out.println(" Номер | ФИО              |  Должность  | Год");
        System.out.println("-------+------------------+-------------+-----");
        for (var e : out) {
            if (e.getPosition().equalsIgnoreCase(position)){
                System.out.printf("%-7s| %-16s |%-12s |%4s\n", e.getId(), e.getFullName(), e.getPosition(), e.getHireDate());
            }
        }
        return out;
    }

Ответы (1 шт):

Автор решения: Дмитрий

Все слишком сложно, захордкожено и нерационально.

Попробуйте так:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class EmployeeCollection {

    public static void main(String[] args) {
        
        String sourceFileName = "input.txt";
        String targetFileName = "output.txt";

        List<Employee> employes = read(sourceFileName, line -> {
            final String [] personList = line.split(" ");
            return new Employee(Integer.parseInt(personList[0]), personList[1], personList[2], Integer.parseInt(personList[3]));
        });
        
        System.out.print("Введите должность сотрудника: ");        
        System.out.println(" Номер | ФИО              |  Должность  | Год");
        System.out.println("-------+------------------+-------------+-----");
        String position = new Scanner(System.in).nextLine();
        for (Employee e : employes) {
            if (e.getPosition().equalsIgnoreCase(position)) 
                System.out.printf("%-7s| %-16s |%-12s |%4s\n", e.getId(), e.getFullName(), e.getPosition(), e.getHireDate());
        }
        
        write(targetFileName, employes, e->e.getPosition().equalsIgnoreCase(position));

    }

    private static <T> List<T> read(String filePath, Function<String, T> function) {
        try (Stream<String> lineStream = Files.lines(Paths.get(filePath))) {
            return lineStream
                    .map(function)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static <T> void write(String filePath, Iterable<T> itrb, Predicate<T> predicate) {
        try {
            final List<String> result = StreamSupport.stream(itrb.spliterator(), false)
                    .filter(predicate)
                    .map(String::valueOf)
                    .collect(Collectors.toList());
            Files.write(Paths.get(filePath), result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

Не забудьте переопределить метод ToString() для класса Employee, чтобы определить вид строки в записываемом файле

→ Ссылка