Java第十六课_IO流

发布时间 2023-12-22 23:23:12作者: 张心野

1.Collections常用工具

  • Collections常用工具

        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("ddd");
            list.add("aaa");
            list.add("bbb");
            list.add("ccc");
            // static <T> boolean  addAll(Collection<? super T> c, T... elements)
            //           将所有指定元素添加到指定 collection 中。
            Collections.addAll(list,"eee","fff","ggg");
            System.out.println(list);
            System.out.println("------------------------------");
    
            // static <T> int  binarySearch(List<?> list, T key)
            //           使用二分搜索法搜索指定列表,以获得指定对象。
            // static <T> int  binarySearch(List<?> list, T key, Comparator<? > c)
            //           使用二分搜索法搜索指定列表,以获得指定对象。
            // 折半查找中 数组或集合要升序排列
            Collections.sort(list);
            System.out.println("list = " + list);
            int index = Collections.binarySearch(list, "ddd");
            System.out.println("index = " + index);
            index = Collections.binarySearch(list, "000");
            System.out.println("index = " + index);
            System.out.println("------------------------------");
    
            // static <T> void  copy(List<? super T> dest, List<? extends T> src)
            //           将所有元素从src列表复制到dest列表。
            List<String> list1 = new ArrayList<>();
            Collections.addAll(list1, "111", "222", "333");
            Collections.copy(list, list1);// 会把原先元素覆盖, 如果src小的话, 后面的部分保留
            System.out.println("list = " + list);
            System.out.println("list1 = " + list1);
            System.out.println("------------------------------");
    
            // static <T> void  fill(List<? super T> list, T obj)
            //           使用指定元素替换指定列表中的所有元素。
            Collections.fill(list1, "000");
            System.out.println("list1 = " + list1);
            System.out.println("------------------------------");
    
            // static int indexOfSubList(List<?> source, List<?> target) 求整个target在source里的索引(开头)
            // static int lastIndexOfSubList(List<?> source, List<?> target)
            list.addAll(list1);
            System.out.println("list = " + list);
            int index1 = Collections.indexOfSubList(list, list1);
            System.out.println("index1 = " + index1);
            System.out.println("------------------------------");
    
            // static <T extends Object & Comparable<? super T>> T  max(Collection<? extends T> coll)
            //           根据元素的自然顺序,返回给定 collection 的最大元素。
            // static <T> T  max(Collection<? extends T> coll, Comparator<? super T> comp)
            //           根据指定比较器产生的顺序,返回给定 collection 的最大元素。
            // static <T extends Object & Comparable<? super T>>  T  min(Collection<? extends T> coll)
            //           根据元素的自然顺序 返回给定 collection 的最小元素。
            // static <T> T  min(Collection<? extends T> coll, Comparator<? super T> comp)
            String min = Collections.min(list);
            System.out.println("min = " + min);
            String max = Collections.max(list);
            System.out.println("max = " + max);
    
            Collections.addAll(list1, "fdsa", "fdskaljh", "fgisdh", "fgyewfgy", "css");
            System.out.println("list1 = " + list1);
            String max1 = Collections.max(list1, (x, y) -> Integer.compare(x.length(), y.length()));
            System.out.println("max1 = " + max1);
            System.out.println(Collections.min(list1, Comparator.comparingInt(String::length)));
            System.out.println("------------------------------");
    
            // static <T> boolean  replaceAll(List<T> list, T oldVal, T newVal)
            //           使用另一个值替换列表中出现的所有某一指定值。
            boolean xyz = Collections.replaceAll(list1, "000", "xyz");
            System.out.println("xyz = " + xyz);
            System.out.println("list1 = " + list1);
            System.out.println("------------------------------");
    
            // static void reverse(List<?> list)
            //           反转指定列表中元素的顺序。
            Collections.sort(list1);
            System.out.println(list1);
            Collections.reverse(list1);
            System.out.println(list1);
            System.out.println("------------------------------");
    
            // void shuffle(List<?> list)  类似洗牌
            //           使用默认随机源对指定列表进行置换。
            // Collections.shuffle(list1);
            // System.out.println(list1);
    
            // static <T extends Comparable<? super T>>  void  sort(List<T> list)
            //           根据元素的自然顺序 对指定列表按升序进行排序。
            // static <T> void   sort(List<T> list, Comparator<? super T> c)
            //
    
            // static void swap(List<?> list, int i, int j)
            //           交换列表指定位置的两个元素。
            Collections.swap(list1, 0, list1.size() - 1);
            System.out.println(list1);
    
            // static <T> Collection<T>  synchronizedCollection(Collection<T> c)
            //           返回指定 collection 支持的同步(线程安全的)collection。
            // static <T> List<T>  synchronizedList(List<T> list)
            //           返回指定列表支持的同步(线程安全的)列表。
            // static <K,V> Map<K,V>  synchronizedMap(Map<K,V> m)
            //           返回由指定映射支持的同步(线程安全的)映射。
            // static <T> Set<T>  synchronizedSet(Set<T> s)
        }
    

2.IO流

  • OutputStream

        public static void main(String[] args) throws IOException {
            // IO流 : 数据持久化
            /*
                I : Input 输入 , 编写的程序读取数据到内存中
                O : Output 输出 , 编写的程序将内存中的数据输出到其他地方(硬盘,用户端)
                流向是相对于程序而言
    
                按照操作数据的单位进行划分 :
                    字节流  一个字节一个字节操作 , 可以操作所有类型文件                Stream 结尾
                    字符流  一个字符一个字符操作 , 只能操作 文本文件(纯文字的文件)       Reader/Writer 结尾
    
                注意 : 电脑在存储数据时,是按字节存储,所有文件都是 字节
    
                按功能 :
                    文件流
                    数据流
                    对象流
                    缓冲流
                    过滤流
                    ...
             */
            // 将数据写入硬盘 :
            // 输出流 :
            // OutputStream : 此抽象类是表示输出字节流的所有类的超类。
    
            // FileNotFoundException : 输出流抛出该异常的条件 : 1.文件不存在,且指定位置不可创建 2.文件存在,但不可用3.指定目录不存在
            // 文件位置 :
            // 1.绝对路径 : F:/aa/a.txt
            // 2.相对路径 : Java程序中 IO流默认的相对路径 是从 当前项目工程名 开始计算的, 会创建在工程里
    
            // 输出流在创建对象时的三件事 : a.内存中创建流对象 b.查看指定文件是否存在,不存在就创建 c.将流对象和文件关联起来
            OutputStream outputStream = new FileOutputStream("a.txt");
    
            //  void write(int b) 该函数只能写最右边的一个字节
            //           将指定的字节写入此输出流。
            outputStream.write('A');
            outputStream.write(100);// a 97
    
            //  void write(byte[] b)
            //           将 b.length 个字节从指定的 byte 数组写入此输出流。
            byte[] bytes = "华夏ABC".getBytes();
            outputStream.write(bytes);
            System.out.println(Arrays.toString(bytes));
    
            //  void write(byte[] b, int off, int len)
            //           将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
            outputStream.write(bytes, 3, 5);
    
            //  void flush()    缓冲流刷新缓冲区使用
            //           刷新此输出流并强制写出所有缓冲的输出字节。
            outputStream.flush();
    
            //   void close() 1.就是将内存流对象和文件解绑 2.具备 flush() 函数的功能
            //           关闭此输出流并释放与此流有关的所有系统资源。
            outputStream.close();
        }
    
  • InputStream

        public static void main(String[] args) throws IOException {
            // InputStream : 此抽象类是表示字节输入流的所有类的超类。
            //      FileInputStream :
            // FileNotFoundException : 输入流中,文件不存在直接抛异常
            InputStream inputStream = new FileInputStream("a.txt");
    
            // int read()  如果已到达文件末尾,则返回 -1。
            //           从此输入流中读取一个数据字节。
            int read = inputStream.read();
            System.out.println("read = " + read);
            read = inputStream.read();
            System.out.println("read = " + read);
            read = inputStream.read();
            System.out.println("read = " + read);
    
            //  int read(byte[] b) : 返回值是读取到的数据的长度
            //           从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
            byte[] bytes = new byte[10];// 开发中 : 1024的倍数
            System.out.println("Arrays.toString(bytes) = " + Arrays.toString(bytes));
            int len = inputStream.read(bytes);
            System.out.println("len = " + len);
            System.out.println("Arrays.toString(bytes) = " + Arrays.toString(bytes));
            len = inputStream.read(bytes);
            System.out.println("len = " + len);
            System.out.println("Arrays.toString(bytes) = " + Arrays.toString(bytes));
    
            //  int read(byte[] b, int off, int len)
    
            // void close()
            //           关闭此文件输入流并释放与此流有关的所有系统资源。
            inputStream.close();
        }
    
  • CopyFile方法

    public class Practice03CopyFile {
    
        public static void main(String[] args) throws IOException {
            // 将桌面图片拷贝到当前工程目录下
            fileCopy1("C:\\Users\\张晗\\Desktop\\闲云\\1221/01.png","3.png");
            fileCopy2("C:\\Users\\张晗\\Desktop\\闲云\\1221/01.png","4.png");
    
        }
    
        public static void fileCopy1(String srcFile,String destFile) throws IOException {
            FileInputStream fileInputStream = new FileInputStream(srcFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);
            // 边读边写
            // 每次读写一个字节
            int len;
            while ((len = fileInputStream.read()) != -1) {
                fileOutputStream.write(len);
            }
            fileOutputStream.close();
            fileInputStream.close();
        }
    
        public static void fileCopy2(String srcFile,String destFile) throws IOException {
            FileInputStream fileInputStream = new FileInputStream(srcFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);
            // 边读边写
            // 借助数组提升效率
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
            fileOutputStream.close();
            fileInputStream.close();
        }
    }
    
  • ObjectOutputStream

    public class Practice04ObjectIO {
    
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            // 类直接输入输出的话, java不可能认识类的格式, 无法正常输出
            // ObjectIO: 类输入输出IO
            //      需要类实现Serializable接口(只是一个标识, 无需真正实现)
            User user = new User("kitty2", 22);
    
            // 对象输出流 : ObjectOutputStream
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("b.txt"));
            objectOutputStream.writeObject(user);
            objectOutputStream.close();
    
            // 对象输入流 : ObjectInputStream
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("b.txt"));
            User user1  = (User) objectInputStream.readObject();
            objectInputStream.close();
            System.out.println("user1 = " + user1);
        }
    }
    
    public class User implements Serializable {
    
        private String name;
        private Integer age;
    
        public User(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
  • BufferedStream

    public class Practice05BUfferIO {
    
        public static void main(String[] args) throws IOException {
            // 缓冲流 :
            // BufferedInputStream
            // BufferedOutputStream
            // 文件拷贝
    
            fileCopy("C:\\Users\\张晗\\Desktop\\闲云/z.txt", "h.txt");
        }
    
        public static void fileCopy(String srcFile, String destFile) {
            // JDK7.0 开始  : 支持try() 即 try witch resource 格式
            //      在()里声明的资源, 会自动释放.
            //          除了方便, 还能防止声明资源前出错, 导致finally体中释放也出错的问题
            try (
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile));
            ){
                int len;
                byte[] bytes = new byte[1024];
                while((len = bufferedInputStream.read(bytes)) != -1){
                    bufferedOutputStream.write(bytes, 0, len);
                    bufferedOutputStream.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  • DataIO

        public static void main(String[] args) throws IOException {
            // int数据 写入硬盘
            FileOutputStream fileOutputStream = new FileOutputStream("b.txt");
    
            // int数据四个字节,需要一次一个字节写
            fileOutputStream.write(Integer.MAX_VALUE >> 24);
            fileOutputStream.write(Integer.MAX_VALUE >> 16);
            fileOutputStream.write(Integer.MAX_VALUE >> 8);
            fileOutputStream.write(Integer.MAX_VALUE);
            fileOutputStream.close();
    
            // 数据流 Data : 对基本数据类型进行操作
            // 数据序列化 : 数据 ---> 字节
            // 数据反序列化 : 字节 ---> 数据
            // 基本数据类型 --->  硬盘
            // 读取 int 型的最大值
            // 数据输入流 : DataInputStream
            DataInputStream dataInputStream = new DataInputStream(new FileInputStream("b.txt"));
            int max = dataInputStream.readInt();
            System.out.println("max = " + max);
            System.out.println(Integer.MAX_VALUE);
            dataInputStream.close();
    
            DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("c.txt"));
            dataOutputStream.writeInt(Integer.MIN_VALUE);
            dataOutputStream.writeLong(Long.MAX_VALUE);
            dataOutputStream.writeDouble(Math.PI);
            dataOutputStream.close();
    
            dataInputStream = new DataInputStream(new FileInputStream("c.txt"));
            System.out.println(dataInputStream.readInt());
            System.out.println(dataInputStream.readLong());
            System.out.println(dataInputStream.readDouble());
            dataInputStream.close();
        }