Stream系列(十五)File方法使用

文件读写

视频讲解:https://www.bilibili.com/video/av78612785/

Stream系列(十五)File方法使用_第1张图片

EmployeeTestCase.java
package com.example.demo;

import lombok.extern.log4j.Log4j2;
import org.junit.Test;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
public class EmployeeTestCase extends BaseTestCase {
    @Test
    public void writeRead() throws IOException {
        //写入文件
        PrintWriter printWriter = new PrintWriter(Files.newBufferedWriter(Paths.get("E://text.txt")));
        list.stream().forEach(printWriter::println);
        printWriter.close();
        //读取文件
        List content = Files.lines(Paths.get("E://text.txt")).peek(System.out::println).collect(Collectors.toList());
    }

}
BaseTestCase.java
package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class BaseTestCase {
    protected static final List list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));
}

结果:

Employee(id=1, name=Alex, salary=1000.0)
Employee(id=2, name=Michael, salary=2000.0)
Employee(id=3, name=Jack, salary=1500.0)
Employee(id=4, name=Owen, salary=1500.0)
Employee(id=5, name=Denny, salary=2000.0)

关注公众号,坚持每天3分钟视频学习

Stream系列(十五)File方法使用_第2张图片

 

 

你可能感兴趣的:(Stream系列(十五)File方法使用)