RandomAccessFile 、 lambda表达式、Stream流

RandomAccessFile

一种操作文件的类,可以操控文件内的指针位置。
/**

  • RandomAccessFile使用
  • 构造函数
  • public RandomAccessFile(String name, String mode)
  • public RandomAccessFile(File file, String mode)
  • mode
  • “r” 以只读打开
  • “rw” 可读可写
  • “rws” 可读可写 文件的内容 文件元数据的更新都会同步到基础存储设备
  • “rwd” 可读可写 文件的内容更新都会同步到基础存储设备
  • void getFilePointer() 返回文件记录指针的位置
  • void seek(long pos) 文件指针定位到pos位置
  • 1)随机读取文件中某一部分的数据
  • 2)在指定位置去追加一段数据 50 图论教育
  • RandomAccessFile 输入流/输出流
  • 1)RandomAccessFile可以自由访问文件中任意位置 可以访问文件中部分内容
  • 2)RandomAccessFile对象进行读写的时候,文件记录指针自动往后移动
  • 3)输出流flush/close 文件内容同步修改到基础设备
  • RandomAccessFile->rwd rws 文件内容同步修改到基础设备
  • 注意:更
package io;

import java.io.*;

改文件内容是否立即同步取决于系统底层实现
 */
public class TestDemo8 {
    
    
    public static void main(String[] args) {
    
    
        FileInputStream fis = null;
        FileOutputStream fos = null;
        RandomAccessFile file = null;
        //在指定位置去追加一段数据
        try {
    
    
            file = new RandomAccessFile("a.txt", "rw");
            //移动文件指针
            file.seek((long)(Math.random() * file.length()));
            //获取随机文件指针的位置
            long filePointer = file.getFilePointer();
            System.out.println("init: "+filePointer);

            //file.write("图论软件".getBytes()); //覆盖原文件内容
            /**
             * 保存文件指针之后的数据 写入一个临时文件 File createTmpFile
             * 追加
             * 将临时文件的数据追加到原文件之后
             */
            //创建临时文件
            File tempFile = File.createTempFile("tmp", ".txt", new File("/tmp"));//默认不是在当前路径创建临时文件 /tmp
            //linux下/tmp保存临时文件的目录

            //创建输入、输出流
            fis = new FileInputStream(tempFile.getAbsolutePath());
            fos = new FileOutputStream(tempFile.getAbsolutePath());

            //保存文件指针之后的数据到临时文件中
            byte[] bytes = new byte[256];
            int hasRead = 0;
            while((hasRead = file.read(bytes)) != -1){
    
    
                fos.write(bytes, 0, hasRead);
            } //使用RandomAccessFile对象读的过程中文件指针往后走

            //在指定位置追加内容
            System.out.println("after read: "+file.getFilePointer());
            file.seek(filePointer);
            file.write("图论软件".getBytes()); //write写的过程中文件指针是否会往后走

            //将临时文件的数据追加到原文件之后
            System.out.println("after write: "+file.getFilePointer());
            while((hasRead = fis.read(bytes)) != -1){
    
    
                file.write(bytes, 0, hasRead);
            }
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                fis.close();
                fos.close();
                file.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }

        try {
    
    
            //随机读取文件中某一部分的数据
            File f = new File("a.txt");
            RandomAccessFile file = new RandomAccessFile(f, "r");
            file.seek((long)(Math.random() * f.length()));
            //获取文件指针的位置
            System.out.println(file.getFilePointer());

            byte[] bytes = new byte[256];
            int hasRead = file.read(bytes); // <=256
            System.out.println(new String(bytes, 0, hasRead));
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

lambda表达式

/**

  • lambda表达式
  • java1.8出现 让我们用更加简洁流畅的代码完成功能
  • eg. TestLambda lambda2 = ()-> System.out.println(“test lambda”);
  • =左边 函数式接口的引用
  • =右边 lambda表达式
  • () 方法的参数
  • -> lambda操作符
  • ->之后 方法的实现
  • Comparator接口
  • String[] strs = “shhs Ihhjdh iwjjjd AJhjhhhs bjfhdh”.split(" ");
  • Arrays.sort(strs, new Comparator(){
 *     @Override
 *     public int compare(String s1, String s2){
    
    
 *         return s1.toLowerCase().compareTo(s2.toLowerCase());
 *     }
 * });
 *
  • 课堂练习:修改上面Comparotor接口的实现为lambda表达式
  • (String s1,String s2)-> s1.toLowerCase().compareTo(s2.toLowerCase())
    */
package io;

import java.util.Arrays;
import java.util.function.Function;


//函数式接口
@FunctionalInterface
interface TestLambda{
    
    
    void func();
    //void fun1();
}

@FunctionalInterface
interface TestLambda1{
    
    
    void func();
    //void fun1();
}
public class TestDemo9 {
    
    
    public static void func(Function<Integer, Integer>function){
    
    

    }
    public static void main(String[] args) {
    
    
        TestLambda lambda1 = new TestLambda(){
    
    
            @Override
            public void func() {
    
    
                System.out.println("fun");
            }

//            @Override
//            public void fun1() {
    
    
//                System.out.println("fun1");
//            }
        };
        //lambda表达式
        TestLambda1 lambda2 = ()-> System.out.println("test lambda");

       //func((x, y) -> x+y);//实现x+y这样的函数  ???

        String[] strs = "shhs Ihhjdh iwjjjd AJhjhhhs bjfhdh".split(" ");
        Arrays.sort(strs, (String s1, String s2)-> s2.toLowerCase().compareTo(s1.toLowerCase()));
        System.out.println(Arrays.toString(strs));

    }
}

Stream流

  • Stream
  • 使用函数式编程模式,对集合进行操作
  • 1)中间操作 会使用流方法再次返回一个流,我们可以链接多个中间操作,同时不用加分号
  • 2)终端操作 会流操作的结束动作,返回一个非流的结果 forEach
  • Stream用来计算数据 主要和CPU打交道
  • Collection负责存储数据 主要和内存打交道
  • Stream操作步骤
  • 1)获取一个stream
    1. 使用stream操作数据 中间操作的中间链 一个终止操作(执行中间操作的中间链返回最终结果)
      */
class Student{
    
    
    private Integer id;
    private String name;
    private Integer age;
    private Double score;

    public Student(Integer id, String name, Integer age, Double score) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Integer getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

    public Integer getAge() {
    
    
        return age;
    }

    public Double getScore() {
    
    
        return score;
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id) &&
                Objects.equals(name, student.name) &&
                Objects.equals(age, student.age) &&
                Objects.equals(score, student.score);
    }

    @Override
    public int hashCode() {
    
    
        return Objects.hash(id, name, age, score);
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
public class TestDemo10 {
    
    
    public static List<Student> getStudents(){
    
    
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(1, "小白", 25, 89.5));
        students.add(new Student(2, "小李", 18, 99.5));
        students.add(new Student(3, "小蔡", 20, 69.5));
        students.add(new Student(4, "小花", 22, 55.5));
        students.add(new Student(5, "小名", 23, 90.5));
        students.add(new Student(3, "小蔡", 20, 69.5));
        return students;
    }
    public static void main(String[] args) {
    
    
        //创建stream
        //通过一个集合的stream方法创建流
        List<Student> students = getStudents();
        Stream<Student> stream = students.stream();
        
        //另外两种创建Stream流的方法
                //Stream.of
        Stream<Student> stream1 = Stream.of(new Student(1, "小白", 25, 89.5),
                  new Student(2, "小李", 18, 99.5),
                  new Student(3, "小蔡", 20, 69.5));
        //通过数组创建stream
        Student[] studentsArr = (Student[]) getStudents().toArray();
        Stream<Student> stream2 = Arrays.stream(studentsArr);
        Stream操作数据

     * filter: 接受一个lambda表达式,从流中进行过滤
     * limit: 截断流,筛选出前N条数据
     * skip: 跳过前N个元素
     * distinct: 筛选,通过流生成元素的hashCode()和equals()去除重复的元素
     */
        过滤出年龄小于22的同学
        stream.filter(student -> student.getAge() < 22).forEach(System.out::println);
        stream.limit(3).forEach(System.out::println);
        stream.skip(2).forEach(System.out::println);
        stream.distinct().forEach(System.out::println);

/**
* map 接受lambda 将元素转换为其他形式,接受一个函数作为参数,该函数会被应用
* 到每个元素上,并且映射成一个新元素
*
* sorted ->自然排序
* sorted -> 定制排序
*/

 根据成绩从小到大进行排序
        stream.sorted((s1, s2)-> (int)(s1.getScore()-s2.getScore())).forEach(System.out::println);

/**
* 终端操作
* 匹配和查找的方法
* allMatch 检查是否匹配所有元素
* anyMathch 检查是否至少匹配一个元素
* noneMath 检查是否没有匹配所有元素
* findFirst 返回第一个元素
* count 返回流中元素的总个数
* max 返回流中最大值
* min 返回流中最小值
*/

        boolean b1 = stream.allMatch(student -> student.getAge() > 20);
        System.out.println(b1);
        System.out.println(stream.findFirst());
        System.out.println(stream.count());
        System.out.println(stream.max((s1, s2)-> (int)(s1.getScore()-s2.getScore())));
        List<String> list = Arrays.asList("djh", "wkjd", "c3",  "b1", "c1", "c2");
        //获取集合的流
        list.stream()
                .filter((s) -> s.startsWith("c")) //执行过滤,过滤出以c开头的字符串 //c3 c1 c2
                .map((s) -> s.toUpperCase()) //转换成大写 //C3 C1 C2
                .sorted() //排序  //C1 C2 C3
                .forEach(System.out::println); //for循环打印

猜你喜欢

转载自blog.csdn.net/weixin_47198561/article/details/113279674