IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 泛型+IO流+网络编程 -> 正文阅读

[网络协议]泛型+IO流+网络编程

泛型+IO流+网络编程
6.5-8.15



一、泛型

  • 相当于 标签

  • 所谓泛型,就是允许在定义类、接口时通过一个标识表示类中某个属性的类
    型或者是某个方法的返回值及参数类型
    。这个类型参数将在使用时(例如,
    继承或实现这个接口,用这个类型声明变量、创建对象时)确定(即传入实
    际的类型参数,也称为类型实参)。

  • 若不符合在编译的时候就会报错

  • 样子:<类型>

  • 原因就是new的对象在底层原码的时候就有一个< E >样子的东西,有几个就声明几个,如Map要声明两个

  • 左边声明了泛型,右边可省略

泛型的使用

1.jdk 5.0新增的特性

2.在集合中使用泛型:
总结:

  • ① 集合接口或集合类在jdk5.0时都修改为带泛型的结构。
  • ② 在实例化集合类时,可以指明具体的泛型类型
  • ③ 指明完以后,在集合类或接口中凡是定义类或接口时,内部结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型。
    比如:add(E e) —>实例化以后:add(Integer e)
  • ④ 注意点:泛型的类型必须是类,不能是基本数据类型。需要用到基本数据类型的位置,拿包装类替换
  • ⑤ 如果实例化时,没有指明泛型的类型。默认类型为java.lang.Object类型。
    //在集合中使用泛型之前的情况:
    @Test
    public void test1(){
        ArrayList list = new ArrayList();
        //需求:存放学生的成绩
        list.add(78);
        list.add(76);
        list.add(89);
        list.add(88);
        //问题一:类型不安全
//        list.add("Tom");

        for(Object score : list){
            //问题二:强转时,可能出现ClassCastException
            int stuScore = (Integer) score;
            System.out.println(stuScore);
        }
    }
    
    //在集合中使用泛型的情况:以ArrayList为例
    @Test
    public void test2(){
       ArrayList<Integer> list =  new ArrayList<Integer>();//规定类型为Integer

        list.add(78);
        list.add(87);
        list.add(99);
        list.add(65);
        //编译时,就会进行类型检查,保证数据的安全
//        list.add("Tom");

        //方式一:
//        for(Integer score : list){
//            //避免了强转操作
//            int stuScore = score;
//            System.out.println(stuScore);
//        }
        //方式二:
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            int stuScore = iterator.next();
            System.out.println(stuScore);
        }
    }

练习:
主要看类名部分以及compareTo部分的改变

public class Employee implements Comparable<Employee>{
    private String name;
    private int age;
    private MyDate birthday;

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public Employee() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    //指明泛型时的写法
    @Override
    public int compareTo(Employee o) {
        return this.name.compareTo(o.name);
        //就不用判断是不是Employee,因为泛型已经规定了
    }

    //没有指明泛型时的写法
    //按 name 排序
//    @Override
//    public int compareTo(Object o) {
//        if(o instanceof Employee){
//            Employee e = (Employee)o;
//            return this.name.compareTo(e.name);
//        }
        return 0;
//        throw new RuntimeException("传入的数据类型不一致!");
//    }
}

/**
 * 创建该类的 5 个对象,并把这些对象放入 TreeSet 集合中(下一章:TreeSet 需使用泛型来定义)
 分别按以下两种方式对集合中的元素进行排序,并遍历输出:

 1). 使Employee 实现 Comparable 接口,并按 name 排序
 2). 创建 TreeSet 时传入 Comparator对象,按生日日期的先后排序。

 *
 * @author shkstart
 * @create 2019 上午 10:23
 */
public class EmployeeTest {

    //问题二:按生日日期的先后排序。
    @Test
    public void test2(){

        TreeSet<Employee> set = new TreeSet<>(new Comparator<Employee>() {
            
            //使用泛型以后的写法:不必写(o1 instanceof Employee && o2 instanceof Employee)也不必强转,直接加上内容即可
            @Override
            public int compare(Employee o1, Employee o2) {
                MyDate b1 = o1.getBirthday();
                MyDate b2 = o2.getBirthday();

                return b1.compareTo(b2);
            }
            
            //使用泛型之前的写法
            //@Override
//            public int compare(Object o1, Object o2) {
//                if(o1 instanceof Employee && o2 instanceof Employee){
//                    Employee e1 = (Employee)o1;
//                    Employee e2 = (Employee)o2;
//
//                    MyDate b1 = e1.getBirthday();
//                    MyDate b2 = e2.getBirthday();
//                    //方式一:
                    //比较年
                    int minusYear = b1.getYear() - b2.getYear();
                    if(minusYear != 0){
                        return minusYear;
                    }
                    //比较月
                    int minusMonth = b1.getMonth() - b2.getMonth();
                    if(minusMonth != 0){
                        return minusMonth;
                    }
                    //比较日
                    return b1.getDay() - b2.getDay();
//
//                    //方式二:
//                    return b1.compareTo(b2);
//
//                }
                return 0;
//                throw new RuntimeException("传入的数据类型不一致!");
//            }
        });

        Employee e1 = new Employee("liudehua",55,new MyDate(1965,5,4));
        Employee e2 = new Employee("zhangxueyou",43,new MyDate(1987,5,4));
        Employee e3 = new Employee("guofucheng",44,new MyDate(1987,5,9));
        Employee e4 = new Employee("liming",51,new MyDate(1954,8,12));
        Employee e5 = new Employee("liangzhaowei",21,new MyDate(1978,12,4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator<Employee> iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }


    //问题一:使用自然排序
    @Test
    public void test1(){
        TreeSet<Employee> set = new TreeSet<Employee>();

        Employee e1 = new Employee("liudehua",55,new MyDate(1965,5,4));
        Employee e2 = new Employee("zhangxueyou",43,new MyDate(1987,5,4));
        Employee e3 = new Employee("guofucheng",44,new MyDate(1987,5,9));
        Employee e4 = new Employee("liming",51,new MyDate(1954,8,12));
        Employee e5 = new Employee("liangzhaowei",21,new MyDate(1978,12,4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator<Employee> iterator = set.iterator();
        while (iterator.hasNext()){
            Employee employee = iterator.next();
            System.out.println(employee);
        }
    }
}

3.如何自定义泛型结构: 泛型类、泛型接口;泛型方法。见 GenericTest1.java

(1)泛型类:就是具有一个或多个类型变量的类

  • 尖括号<>;
  • T称为类型变量;
  • T可以制定方法的返回类型,变量的类型,域的类型;
//泛型类
public class Order<T> {
    int age;
    String name;

    T number;//即不确定number的类型,先用T代替

    //类的内部结构就可以使用类的泛型
    public Order(){

    }
    public Order(String name,int age,T number){
        this.age = age;
        this.name = name;
        this.number = number;
    }

    public T getNumber() {
        return number;
    }

    public void setNumber(T number) {
        this.number = number;
    }
}


注意点:

  1. 如果定义了泛型类,实例化没有指明类的泛型,则认为此泛型类型为Object类型。
    要求:如果大家定义了类是带泛型的,建议在实例化时要指明类的泛型。
        Order order = new Order();
        order.setNumber("aa");
        order.setNumber(2);

        //建议:实例化时指明类的泛型
        Order<String> order1 = new Order<String>("orderAA",1001,"order:AA");
        order1.setNumber("AA:hello");//只能放String类型是由上边泛型定义有关
  1. 由于子类在继承带泛型的父类时,指明了泛型类型。则实例化子类对象时,不再需要指明泛型。
//SubOrder不是泛型类,实例化对象时不需要显式声明<>
public class SubOrder extends Order<Integer>{
}

//SubOrder是泛型类,实例化对象时需要显式声明<>类型
public class SubOrder1<T> extends Order<T>{
}
public void test2(){
      SubOrder sub1 = new SubOrder();//SubOrder不是泛型类
        //不用再说明泛型了原因就是在定义SubOrder时就已经指明了类型
      SubOrder<Integer> sub2 = new SubOrder<>();
        //但如果在定义子类时也仍然没有讲明类型,则new时需声明
}
  1. 异常类不能声明为泛型类
//(1)
public class MyException<T> extends Exception{
}

//(2)
public void show(){
        //编译不通过
       try{

       }catch(T t){

       }
}
  1. 静态方法中不能使用类的泛型。
public static void show(T orderT){
        System.out.println(orderT);
}
  1. 造数组时
public Order(){
        //编译不通过
//      T[] arr = new T[10];
        //编译通过
        T[] arr = (T[]) new Object[10];
    }
  1. 类型不能用基本数据类型,要用类

  2. 泛型如果不指定,将被擦除,泛型对应的类型均按照Object处理,但不等价
    于Object。经验:泛型要使用一路都用。要不用,一路都不要用

  3. 如果泛型结构是一个接口或抽象类,则不可创建泛型类的对象。

  4. 父类有泛型,子类可以选择保留泛型也可以选择指定泛型类型:
    (1)子类不保留父类的泛型:按需实现

    • 没有类型 擦除
    • 具体类型

    (2)子类保留父类的泛型:泛型子类

    • 全部保留
    • 部分保留
class Father<T1, T2> {
}
// 子类不保留父类的泛型
// 1)没有类型 擦除
class Son1 extends Father {// 等价于class Son extends Father<Object,Object>{
}
// 2)具体类型
class Son2 extends Father<Integer, String> {
}
// 子类保留父类的泛型
// 1)全部保留
class Son3<T1, T2> extends Father<T1, T2> {
}
// 2)部分保留
class Son4<T2> extends Father<Integer, T2> {
}
class Father<T1, T2> {
}
// 子类不保留父类的泛型
// 1)没有类型 擦除
class Son<A, B> extends Father{//等价于class Son extends Father<Object,Object>{
}
// 2)具体类型
class Son2<A, B> extends Father<Integer, String> {
}
// 子类保留父类的泛型
// 1)全部保留
class Son3<T1, T2, A, B> extends Father<T1, T2> {
}
// 2)部分保留
class Son4<T2, A, B> extends Father<Integer, T2> {
}
  1. 泛型不同的引用不能相互赋值。
    @Test
    public void test3(){

        ArrayList<String> list1 = null;
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        //泛型不同的引用不能相互赋值。
//        list1 = list2;
    }

(2)泛型方法
在方法中出现了泛型的结构,泛型参数与类的泛型参数没有任何关系。

换句话说,泛型方法所属的类是不是泛型类都没有关系。
泛型方法,可以声明为静态的。原因:泛型参数是在调用方法时确定的。并非在实例化类时确定。

//以下均不是泛型方法
 public T getNumber() {
        return number;
    }

    public void setNumber(T number) {
        this.number = number;
    }
    @Override
    public String toString() {
        return "Order{" +
                "orderName='" + name + '\'' +
                ", orderId=" + age +
                ", orderT=" + number +
                '}';
    }
//泛型方法
//父类
public class Order<T> {
	public static <E>  List<E> copyFromArrayToList(E[] arr){
        ArrayList<E> list = new ArrayList<>();
        for(E e : arr){
            list.add(e);
        }
        return list;
    }
}

//子类
public class SubOrder extends Order<Integer> {//SubOrder:不是泛型类
    public static <E> List<E> copyFromArrayToList(E[] arr){
        ArrayList<E> list = new ArrayList<>();
        for(E e : arr){
            list.add(e);
        }
        return list;
    }
}


//测试泛型方法
	@Test
	public void test4(){
    	Order<String> order = new Order<>();
    	Integer[] arr = new Integer[]{1,2,3,4};
    	//泛型方法在调用时,指明泛型参数的类型。
    	List<Integer> list = order.copyFromArrayToList(arr);
    	System.out.println(list);
	}

泛型方法可以定义为static


泛型在继承方面的体现

虽然类A是类B的父类,但是G< A> 和G < R>二者不具备子父类关系,二者是并列关系。

public class GenericTest {
	@Test
    public void test1(){
//基本数据类型和数组均可因为子父类关系赋值
        Object obj = null;
        String str = null;
        obj = str;

        Object[] arr1 = null;
        String[] arr2 = null;
        arr1 = arr2;
        
        //编译不通过
//        Date date = new Date();
//        str = date;

//        List<Object> list1 = null;
//        List<String> list2 = new ArrayList<String>();
        //此时的list1和list2的类型不具有子父类关系
        //编译不通过
//        list1 = list2;
        /*
        反证法:
        假设list1 = list2;
           list1.add(123);导致混入非String的数据。出错。
         */
		show(list1);
        show1(list2);
	}
	public void show1(List<String> list){
	}

    public void show(List<Object> list){
    }
}

补充:类A是类B的父类,A< G> 是 B< G> 的父类

    @Test
    public void test2(){
//子父类关系:ArrayList-->List-->ArrayList
        AbstractList<String> list1 = null;
        List<String> list2 = null;
        ArrayList<String> list3 = null;

        list1 = list3;
        list2 = list3;

        List<String> list4 = new ArrayList<>();

    }

也就是<>外的可以是子父类,<>内的不能是不同类


通配符

即为
类A是类B的父类,G< A >和G< B >是没有关系的,二者共同的父类是:G<?>

    @Test
    public void test3(){
        List<Object> list1 = null;
        List<String> list2 = null;

        List<?> list = null;

        list = list1;
        list = list2;
    }

    public void print(List<?> list){
        Iterator<?> iterator = list.iterator();
        while(iterator.hasNext()){
            Object obj = iterator.next();//Object是根父类,因此用它接收
            System.out.println(obj);
        }
    }

添加(写入):对于List<?>就不能向其内部添加数据。( 除了添加null之外)

		List<String> list3 = new ArrayList<>();
        list3.add("AA");
        list3.add("BB");
        list3.add("CC");
        list = list3;

//        list.add("DD");
//        list.add('?');
		list.add(null);

获取(读取):允许读取数据,读取的数据类型为Object。

  Object o = list.get(0);
    System.out.println(o);

有限制条件的通配符的使用。
? extends A:
G<? extends A> 相当于 ? <= A

? super A:
G<? super A> 相当于 ? >= A

 	@Test
    public void test4(){

        List<? extends Person> list1 = null;
        List<? super Person> list2 = null;

        List<Student> list3 = new ArrayList<Student>();
        List<Person> list4 = new ArrayList<Person>();
        List<Object> list5 = new ArrayList<Object>();

        list1 = list3;
        list1 = list4;
//        list1 = list5;//不符合list5<=list1

//        list2 = list3;//不符合list2<=list3
        list2 = list4;
        list2 = list5;
    }

必须用大的去接收小的数据
A.add(B); //即B<=A

 	@Test
    public void test4(){
		//读取数据:
        list1 = list3;
        Person p = list1.get(0);
        //编译不通过
        //Student s = list1.get(0);

        list2 = list4;
        Object obj = list2.get(0);
        编译不通过
//        Person obj = list2.get(0);

        //写入数据:
        //编译不通过
//        list1.add(new Student());

        //编译通过
        list2.add(new Person());
        list2.add(new Student());

    }

注意点:

//注意点1:编译错误:不能用在泛型方法声明上,返回值类型前面<>不能使用?
public static <?> void test(ArrayList<?> list){
}
//注意点2:编译错误:不能用在泛型类的声明上
class GenericTypeClass<?>{
}
//注意点3:编译错误:不能用在创建对象上,右边属于创建集合对象
ArrayList<?> list2 = new ArrayList<?>();

二、I/O流

1.File类的使用

如何创建file实例

  1. 如何创建File类的实例
    File(String filePath)
    File(String parentPath,String childPath)
    File(File parentFile,String childPath)

public File(String pathname)
以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果
pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。

public File(String parent,String child)
以parent为父路径,child为子路径创建File对象。

public File(File parent,String child)
根据一个父File对象和子文件路径创建File对象

  1. 相对路径: 相较于某个路径下,指明的路径。
    绝对路径: 包含盘符在内的文件或文件目录的路径

  2. 路径分隔符
    windows : \ \
    unix: /

	@Test
    public void test1(){
        //构造器1
        File file1 = new File("hello.txt");//相对于当前module
        File file2 =  new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt");

        System.out.println(file1);
        System.out.println(file2);

        //构造器2:
        File file3 = new File("D:\\workspace_idea1","JavaSenior");//路径下 的 文件目录
        System.out.println(file3);

        //构造器3:
        File file4 = new File(file3,"hi.txt");//在路径下 的 文件目录(File3)中的hi.txt
        System.out.println(file4);
    }

常用方法
File类的获取功能

  • public String getAbsolutePath(): 获取绝对路径
  • public String getPath() :获取路径
  • public String getName() :获取名称
  • public String getParent():获取上层文件目录路径。若无,返回null(相对路径不能找上一层)
  • public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
  • public long lastModified() :获取最后一次的修改时间,毫秒值
    @Test
    public void test2(){
        File file1 = new File("hi.txt");
        File file2 = new File("D:\\LABORATORY\\JAVA学习\\6.10IO流");

        System.out.println(file1.getAbsolutePath());//D:\LABORATORY\JAVA学习\6.10IO流\hi.txt
        System.out.println(file1.getPath());//hi.txt
        System.out.println(file1.getName());//hi.txt
        System.out.println(file1.getParent());//null
        System.out.println(file1.length());//0
        System.out.println(new Date(file1.lastModified()));//Thu Jun 10 19:34:16 CST 2021

        System.out.println();

        System.out.println(file2.getAbsolutePath());//D:\LABORATORY\JAVA学习\6.10IO流
        System.out.println(file2.getPath());//D:\LABORATORY\JAVA学习\6.10IO流
        System.out.println(file2.getName());//6.10IO流
        System.out.println(file2.getParent());//D:\LABORATORY\JAVA学习
        System.out.println(file2.length());//0
        System.out.println(new Date(file2.lastModified()));//Thu Jun 10 19:34:43 CST 2021
        System.out.println(file2.lastModified());//1623324883110
    }

如下方法适用于文件目录

  • public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
  • public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组(路径)
@Test
    public void test3(){
        File file = new File("D:\\LABORATORY\\JAVA学习");

        String[] list = file.list();
        for(String s : list){
            System.out.println(s);
        }

        System.out.println();

        File[] files = file.listFiles();
        for(File f : files){
            System.out.println(f);
        }
    }

File类的重命名功能

  • public boolean renameTo(File dest):把文件重命名为指定的文件路径
    比如:file1.renameTo(file2)为例:
    要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
@Test
public void test4(){
    File file1 = new File("hello.txt");//存在
    File file2 = new File("D:\\io\\hi.txt");//不存在

    boolean renameTo = file2.renameTo(file1);
    System.out.println(renameTo);
}

File类的判断功能

  • public boolean isDirectory():判断是否是文件目录
  • public boolean isFile() :判断是否是文件
  • public boolean exists() :判断是否存在(一般在操作前都会先操作判断文件在不在)
  • public boolean canRead():判断是否可读
  • public boolean canWrite():判断是否可写
  • public boolean isHidden() :判断是否隐藏

不存在 \ 否:false
存在 \ 是:true

@Test
    public void test5(){
        File file1 = new File("hello.txt");
        file1 = new File("hello1.txt");

        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());

        System.out.println();

        File file2 = new File("d:\\io");
        file2 = new File("d:\\io1");
        System.out.println(file2.isDirectory());
        System.out.println(file2.isFile());
        System.out.println(file2.exists());
        System.out.println(file2.canRead());
        System.out.println(file2.canWrite());
        System.out.println(file2.isHidden());

    }

File类的创建功能

  • public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
    @Test
    public void test6() throws IOException {
        File file1 = new File("hi.txt");
        if(!file1.exists()){
            //文件的创建
            file1.createNewFile();
            System.out.println("创建成功");
        }else{//文件存在
            file1.delete();
            System.out.println("删除成功");
        }

    }
  • public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。
    如果此文件目录的上层目录不存在,也不创建。
  • public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
    注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目
    路径下。

File类的使用

  1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
  2. File类声明在java.io包下
  3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
  4. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点".

2. IO流原理及流的分类

在这里插入图片描述

  • I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于
    处理设备之间的数据传输
    。如读/写文件,网络通讯等。
  • Java程序中,对于数据的输入/输出操作以“流(stream)” 的
    方式进行。
  • java.io包下提供了各种“流”类和接口,用以获取不同种类的
    数据,并通过标准的方法输入或输出数据。

输入input: 读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
输出output: 将程序(内存)数据输出到磁盘、光盘等存储设备中。

站位在程序的角度看输入、输出
在这里插入图片描述
流的分类

  1. 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
    -字节流用于类似视频、图片的;字符流是char类型,一个一个字符,也就是文本(.txt);
  2. 按数据流的流向不同分为:输入流,输出流
    -对于程序而言
  3. 按流的角色的不同分为:节点流,处理流
    -节点流:作用在数据上,原本没有流,让一个数据流向另一个数据,使其有一个路径;
    -处理流:在节点流基础上包住一层又一层;
    在这里插入图片描述
    在这里插入图片描述

有很多流,但根上的流,主要分为四大类,而这四大类也可通过两个方向来分,其类型均为抽象类
在这里插入图片描述

  • Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个
    抽象基类派生的。
  • 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
    后缀字节流是-Stream,字符流是-er

节点流(或文件流)

FileReader读入数据的基本操作

将IO流文件夹里的hello.txt文件内容读入程序中,并输出到控制台

步骤:
 1.实例化File类的对象(指明要操作的文件)
 2.提供具体的流(建立输送通道)
 3.数据的读入
 4.流的关闭操作(因为会涉及物理连接,所以他不会自动断开

说明:
1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
3. 读入的文件一定要存在,否则就会报FileNotFoundException。

 @Test
    public void testFileReader() { //throws IOException {因为用throw不能保证一定可以关闭流,所以使用try-catch-finally
        FileReader fr = null;
        try {
            //1.实例化File类的对象(指明要操作的文件)
            File file = new File("hello.txt");
            //2.提供具体的流(建立输送通道)
            fr = new FileReader(file);

            //3.数据的读入
            //read():返回读入的一个字符。如果达到文件末尾,返回-1

            //方式1
//        int data = fr.read();
//        while (data != -1){//因为有很多字符所以要循环读取
//            System.out.println((char)data);//因为存的是数,而输出看的是字符,所以要转换
//            data = fr.read();//再读一次看看是不是-1
//        }

            //方式2:语法上的改变而已
            int data;
            while ((data = fr.read()) != -1) {
                System.out.println((char) data);
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally{
            //4.流的关闭操作(因为会涉及物理连接,所以他不会自动断开
          try {
              if(fr != null) {//避免流未实例化,但还去执行关闭操作
                  fr.close();
              }
          }catch (IOException E){
              E.printStackTrace();
          }
          //或
//            if(fr != null){
//                try {
//                    fr.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }

在FileReader中使用read(char[] cbuf)读入数据

对read()操作升级:使用read的重载方法:用数组cbuf[ ]取字符,一节一节要
1.
在这里插入图片描述

@Test
    public void testFileReader1() throws IOException {
        FileReader fr1 = null;
        //1.File类的实例化
        File file1 = new File("hello.txt");
        try {
            //2.FileReader流的实例化
            fr1 = new FileReader(file1);

            //3.读入的操作
            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
            char[] cbuffer = new char[5];//cbuffer:缓冲
            int len;//读几个字符
            while ((len = fr1.read(cbuffer)) != -1 ){//每次读cbuffer数组个字符,最后若不足cbuffer个字符,就读最大数量
                //方式一:
                //错误写法
//            for (int i = 0;i < cbuffer.length;i++){
//                System.out.println(cbuffer[i]);
//            }
                //正确写法
//            for (int i = 0;i < len;i++){
//                System.out.println(cbuffer[i]);
//            }

                //方式二:
                //错误
//                String str = new String(cbuffer);
//                System.out.print(str);
                //正确
                String str = new String(cbuffer,0,len);//每次就印len个
// 它有一个重载方法少用:abstract public int read(char cbuf[], int off, int len) throws IOException;规定每次只能读这么多个即使cbuf有比len长,效率低
                System.out.print(str);
            }
        }catch (IOException E){
            E.printStackTrace();
        }finally {
            //4.资源的关闭
            try {
                if(fr1 != null) {//避免流未实例化,但还去执行关闭操作
                    fr1.close();
                }
            }catch (IOException E){
                E.printStackTrace();
            }
        }
    }

少用:2.
在这里插入图片描述

用FileReader和FileWriter复制文件内容

1.创建File类的对象,指明读入和写出的文件

  • 不能使用字符流来处理图片等字节数据

2.创建输入流和输出流的对象
3.数据的读入和写出操作
4.关闭流资源

//字节流
 @Test
    public void testFileReaderFileWriter() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1.创建File类的对象,指明读入和写出的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");//复制到
             //不能使用字符流来处理图片等字节数据
//            File srcFile = new File("abc.jpg");
//            File destFile = new File("abc1.jpg");

            //2.创建输入流和输出流的对象
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);
            
            //3.数据的读入和写出操作
            char[] cbuf = new char[5];
            int len;//记录每次读入到cbuf数组中的字符的个数
            while ((len = fr.read(cbuf)) != -1){//从srcFile中读取
                //每次写出len个字符
                fw.write(cbuf,0,len);//写到destFile中去
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.关闭流资源
            //方法1:
//            try {
//                if (fw!=null)
//                fw.close();
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }finally {
//                try {
//                    fr.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//             }
//        }
            //方法2:
            try {
                if (fw!=null)
                fw.close();

            } catch (IOException e) {
                e.printStackTrace();
                }
            try {
                if (fr!=null)
                    fr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

使用FileInputStream不能处理文本文件

1.对于文本文件(.txt .java .c .cpp),使用字符流处理
2.对于非文本文件(.jpg .mp3 .mp4 .avi .doc .ppt),使用字节流处理

//如下代码不正确
public class FileInputOutputStreamTest {
    //使用字节流FileInputStream处理文本文件,可能出现乱码
    @Test
    public void testFileInputStream() {
        FileInputStream fis = null;
        try {
            //1.造文件
            File file = new File("hello.txt");
            //2.造流
            fis = new FileInputStream(file);
            //3.读数据
            byte[] buffer = new byte[5];
            int len;//记录每次读取字节的个数
            while((len = fis.read(buffer))!= -1){
                String str = new String(buffer,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                //4.关闭资源
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

使用FileInputStream和FileOutputStream操作非文本文件

字节流
方法1

 /*
    实现对图片、视频的复制过程
     */
    @Test
    public void testFileInputOutputStream(){
    //只能对该文件夹下操作
        File scrFile = new File("photo1.jpg");
        File desFile = new File("photo2.jpg");

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(scrFile);
            fos = new FileOutputStream(desFile);

            //复制过程
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }       
        }
    }

方法2

/*指定路径操作*/
//指定路径下文件的复制
    public void copyFile(String srcPath,String destPath){
        File scrFile = new File(srcPath);
        File desFile = new File(destPath);

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(scrFile);
            fos = new FileOutputStream(desFile);

            //复制过程
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void testCopyFile(){
        long start = System.currentTimeMillis();
        String srcPath = "D:\\LABORATORY\\JAVA学习\\6.10IO流\\片头.mp4";
        String destPath = "D:\\LABORATORY\\JAVA学习\\6.10IO流\\片头3.mp4";
        copyFile(srcPath,destPath);

        long end = System.currentTimeMillis();

        System.out.println("复制的时间为"+(end - start));//63
    }

缓冲流

处理流之一:缓冲流的使用
1.缓冲流
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter

2.缓冲流作用:提供流的读取、写入速度
提高读写速度的原因:内部提供了一个缓冲区

缓冲流实现对非文本文件的复制

时间将比没用缓冲流前短

字节型
方法1

public class BufferTest {
    /*实现非文本文件的复制*/
    @Test
    public void BufferedStreamTest(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File scrFile = new File("photo1.jpg");
            File destFile = new File("photo3.jpg");

            //2.造流
            //2.1造节点流
            FileInputStream fis = new FileInputStream(scrFile);
            FileOutputStream fos = new FileOutputStream(destFile);

            //2.2造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.复制的细节:读取、写入
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //(1)要求:先关闭外层,再关闭内层的流
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //说明:关闭外层流的同时,内层流也会自动关闭,因此内层流的关闭可以省略
//        fos.close();
//        fis.close();
        }

    }
}

方法2

 //实现文件复制的方法
    public void copyFileWithBufferd(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File scrFile = new File(srcPath);
            File destFile = new File(destPath);

            //2.造流
            //2.1造节点流
            FileInputStream fis = new FileInputStream(scrFile);
            FileOutputStream fos = new FileOutputStream(destFile);

            //2.2造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.复制的细节:读取、写入
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //(1)要求:先关闭外层,再关闭内层的流
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //说明:关闭外层流的同时,内层流也会自动关闭,因此内层流的关闭可以省略
//        fos.close();
//        fis.close();
        }
    }
    @Test
    public void testcopyFileWithBufferd(){
        long start = System.currentTimeMillis();
        String srcPath = "D:\\LABORATORY\\JAVA学习\\6.10IO流\\片头.mp4";
        String destPath = "D:\\LABORATORY\\JAVA学习\\6.10IO流\\片头4.mp4";
        copyFileWithBufferd(srcPath,destPath);

        long end = System.currentTimeMillis();

        System.out.println("复制的时间为"+(end - start));//18
    }

字符型

    /*使用BufferedReader和BufferedWriter实现文本文件的复制*/
    @Test
    public void testBufferedReaderWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //造文件+造流
            br = new BufferedReader(new FileReader(new File("hello1.txt")));
            bw = new BufferedWriter(new FileWriter(new File("hello3.txt")));

            //读写操作
            //方式1
            char[] cbuf = new char[1024];
            int len;
            while ((len = br.read(cbuf))!=-1){
                bw.write(cbuf,0,len);
               //bw.flush();没必要,因为满了会自己清空缓存流
            }
            //方式2
            String data;
            while ((data = br.readLine())!=null){
                bw.write(data+"\n");//data不包含换行符
            //或
//                bw.write(data);
//                bw.newLine();//提供换行的操作
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (bw!=null)
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

小练习
1.照片加密与解密
原理:异或操作 m ^ n ^ n = m

public class PicTest {
    /*图片加密*/
    @Test
    public void test1(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("photo1.jpg");
            fos = new FileOutputStream("photo5.jpg");

            byte[] buffer = new byte[20];
            int len;
            while ((len = fis.read(buffer))!=-1){
                //字节数组进行修改
                //错误:因为只是对新的变量进行了改变,而非对原先的进行改变
                for (byte b:buffer){
                    b = (byte)(b^5);
                }
                //正确
                for (int i = 0;i < len;i++){
                    buffer[i] = (byte)(buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /*图片解密*/
    @Test
    public void test2(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("photo5.jpg");
            fos = new FileOutputStream("photo4.jpg");

            byte[] buffer = new byte[20];
            int len;
            while ((len = fis.read(buffer))!=-1){
                //字节数组进行修改
                //错误:因为只是对新的变量进行了改变,而非对原先的进行改变
                for (byte b:buffer){
                    b = (byte)(b^5);
                }
                //正确
                for (int i = 0;i < len;i++){
                    buffer[i] = (byte)(buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

转换流

处理流之二:转换流的使用

1.转换流:属于字符流

  • InputStreamReader:将一个字节的输入流转换为字符的输入流
  • OutputStreamWriter:将一个字符的输出流转换为字节的输出流

2.提供字节流与字符流之间的转换

3.解码:字节、字节数组 —>字符数组、字符串
编码:字符数组、字符串 —>字节、字节数组

4.字符集

  • ASCII:美国标准信息交换码。
    用一个字节的7位可以表示。
  • ISO8859-1:拉丁码表。欧洲码表
    用一个字节的8位表示。
  • GB2312:中国的中文编码表。最多两个字节编码所有字符
  • GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
  • Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
  • UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
/*解码操作*/
    /*InputStreamReader的使用,实现字节的输入流到字符的输入流的转化*/
    @Test
    public void test1(){
        InputStreamReader isr = null;//使用默认的字符集解码
        try {
            FileInputStream fis = new FileInputStream("hello1.txt");
            isr = new InputStreamReader(fis);
//    InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//参数2指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集

            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf))!=-1){
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isr != null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 /*编码过程*/
    /*综合使用 InputStreamReader和OutputStreamWriter*/
    @Test
    public void test2() {
        OutputStreamWriter osw = null;
        InputStreamReader isr = null;
        try {
            File file1 = new File("hello1.txt");
            File file2 = new File("hello4_hbk.txt");

            FileInputStream fis = new FileInputStream(file1);
            FileOutputStream fos = new FileOutputStream(file2);

            isr = new InputStreamReader(fis, "UTF-8");
            osw = new OutputStreamWriter(fos, "gbk");

            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

其他流(了解)

标准的输入、输出流

System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出

System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。

/*
1.3练习:
    从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
    直至当输入“e”或者“exit”时,退出程序。

    方法一:使用Scanner实现,调用next()返回一个字符串
    方法二:使用System.in实现。System.in  --->  转换流 ---> BufferedReader的readLine()

*/
public class OtherStreamTest {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);

            while (true){
                System.out.println("请输入字符串");
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
                    System.out.println("程序结束");
                    break;
                }
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

打印流

PrintStream 和PrintWriter
提供了一系列重载的print() 和 println()
实现将基本数据类型的数据格式转化为字符串输出

@Test
    public void test2() {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
            // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true);
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }

            for (int i = 0; i <= 255; i++) { // 输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    System.out.println(); // 换行
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
    }

数据流

DataInputStream 和 DataOutputStream
作用:用于读取或写出基本数据类型的变量或字符串

练习:将内存中的字符串、基本数据类型的变量写出到文件中。

注意:处理异常的话,仍然应该使用try-catch-finally.

/*写入*/
    @Test
    public void test3() throws IOException {
        //1.
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        //2.
        dos.writeUTF("刘建辰");
        dos.flush();//刷新操作,将内存中的数据写入文件
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
        //3.
        dos.close();
    }

    /*
    将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
    注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
     */
    /*读*/
    @Test
    public void test4() throws IOException {
        //1.
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        //2.
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();

        System.out.println("name = " + name);
        System.out.println("age = " + age);
        System.out.println("isMale = " + isMale);

        //3.
        dis.close();

    }

输入、输出的标准化过程

4.1 输入过程
① 创建File类的对象,指明读取的数据的来源。(要求此文件一定要存在)
② 创建相应的输入流,将File类的对象作为参数,传入流的构造器中
③ 具体的读入过程:
创建相应的byte[] 或 char[]。
④ 关闭流资源
说明:程序中出现的异常需要使用try-catch-finally处理。

4.2 输出过程
① 创建File类的对象,指明写出的数据的位置。(不要求此文件一定要存在)
② 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
③ 具体的写出过程:
write(char[]/byte[] buffer,0,len)
④ 关闭流资源
说明:程序中出现的异常需要使用try-catch-finally处理。


对象流

对象流的使用
1.ObjectInputStream 和 ObjectOutputStream
2.作用:用于存储和读取基本数据类型数据或对象的处理流。
它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
包含序列化和反序列化过程

  • 序列化过程: 将内存中的java对象保存到磁盘中或通过网络传输出去
    使用ObjectOutputStream实现对应使用writeObject
  • 反序列化: 将磁盘文件中的对象还原为内存中的一个java对象
    使用ObjectInputStream实现对应使用readObject
public class ObjectInputOutputStreamTest {
    /*序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    * 使用ObjectOutputStream实现*/
    @Test
    public void testObjectOutputStream() {
        ObjectOutputStream oos = null;

            //1.
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
            //2.
            oos.writeObject(new java.lang.String("我爱北京天安门"));//写对象,写出过程
            oos.flush();//刷新操作
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
  

    /*反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    * 使用ObjectInputStream实现*/
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object obj = ois.readObject();
            String str = (String)obj;
            System.out.println(str);//读取打印
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

对象要想实现序列化,需要满足哪几个条件

  1. 实现接口:Serializable 标识接口
  2. 对象所在的类提供常量:序列版本号
  3. 要求对象的属性也必须是可序列化的。(基本数据类型、String:本身就已经是可序列化的。)

随机存取文件流

RandomAccessFile的使用

  1. RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口

  2. RandomAccessFile既可以作为一个输入流,又可以作为一个输出流

  3. 格式:RandomAccessFile(“文件名”,“方式”)
    r: 以只读方式打开
    rw:打开以便读取和写入
    rwd:打开以便读取和写入;同步文件内容的更新
    rws:打开以便读取和写入;同步文件内容和元数据的更新

  4. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
    如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖,向后覆盖)

  5. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果

非文本文件

 @Test
    public void test1() {
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            //1.
            raf1 = new RandomAccessFile("photo1.jpg", "r");
            raf2 = new RandomAccessFile(new File("photo11.jpg"), "rw");
            //2.
            byte[] buffer = new byte[1024];
            int len;
            while ((len = raf1.read(buffer)) != -1) {
                raf2.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.
            if (raf2 != null) {
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (raf1 != null) {
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

文本文件

@Test
    public void test2() {
        try {
            RandomAccessFile raf1 = new RandomAccessFile("hello1.txt", "rw");

            //raf1.seek(3);//将指针调到角标为3的位置
            raf1.seek(raf1.length());//从最后添加
            raf1.write("xyz".getBytes());

            raf1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

使用RandomAccessFile实现数据的插入效果
原理:把指针后的内容复制到StringBuilder中,之后调回指针,覆盖内容,再使用append添加在后边

    @Test
    public void test3() {
        RandomAccessFile raf1 = null;
        try {
            raf1 = new RandomAccessFile("hello.txt", "rw");
            
            //可变的字符序列,用于装buffer的内容,相当于把字符串变成一个容器
            StringBuilder builder = new StringBuilder((int)new File("hello.txt").length());
    
            raf1.seek(2);
            //保存指针2后面的所有数据到StringBuilder中
            byte[] buffer = new byte[20];
            int len;
            while ((len = raf1.read(buffer)) != -1) {
                builder.append(new String(buffer , 0 , len));
            }
            //调回指针,写入“xyz”
            raf1.seek(2);
            raf1.write("xyz" .getBytes());
            //将StringBuilder中的数据写入到文件中
            raf1.write(builder.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf1!=null)
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

使用第三方jar包进行数据读写

即导入jar包,然后调用,就可以减少亲自写内容,例如文件复制直接调用即可,无须如上


三、网络编程

目的:
直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。

一、网络编程中有两个主要的问题:

  • 1.如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
  • 2.找到主机后如何可靠高效地进行数据传输

二、网络编程中的两个要素:
通信双方地址

  • IP:网络中定义的唯一一台主机
  • 端口号:区分一台主机上的不同应用程序

一定的规则(即:网络通信协议。有两套参考模型)

  • OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广
  • TCP/IP参考模型(或TCP/IP协议):事实上的国际标准。

1.对应问题一:IP和端口号
2.对应问题二:提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)
在这里插入图片描述
一个IP对应着哪个类的一个对象? InetAddress

实例化这个类的两种方式是?

  • InetAddress.getByName(String host);
  • InetAddress.getLocalHost();//获取本地ip

两个常用的方法是?

  • getHostName();
  • getHostAddress();

通信要素1:IP和端口号

IP

  1. 定义:唯一的标识 Internet 上的计算机(通信实体)

  2. 在Java中使用InetAddress类代表IP

  3. IP分类:IPv4 和 IPv6 (原因是IPv4不够分,因此出了IPv6来继续分); 万维网 和 局域网

  4. 域名: www.baidu.com www.mi.com www.sina.com www.jd.com
    www.vip.com
    域名->DNS(域名解析服务器,把域名解析成IP地址)->网络服务器

  5. 本地回路地址:127.0.0.1 对应着:localhost

  6. 如何实例化InetAddress两个方法:getByName(String host) 、 getLocalHost()
    两个常用方法:getHostName() 得域名/ getHostAddress()得IP

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            //根据域名查询
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");
            //根据域名获取IP
            InetAddress inet2 = InetAddress.getByName("www.bilibili.com");
            System.out.println(inet2);

            //获取本机IP
            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

端口号

  1. 定义:正在计算机上运行的进程。
  2. 要求:不同的进程有不同的端口号
  3. 范围:被规定为一个 16 位的整数 0~65535。
  4. 端口号与IP地址的组合得出一个网络套接字:Socket

分类

  • 公认端口:0~1023。被预先定义的服务通信占用(如:HTTP占用端口
    80,FTP占用端口21,Telnet占用端口23)
  • 注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占
    用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
  • 动态/私有端口:49152~65535。

通信要素2:网络通信协议

TCP/IP协议簇 以其两个主要协议:传输控制协议(TCP)和网络互联协议(IP)而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议。
IP属于网络层,TCP属于传输层

传输层协议中有两个非常重要的协议:
TCP协议

  • 使用TCP协议前,须先建立TCP连接,形成传输数据通道
  • 传输前,采用“三次握手”方式,点对点通信,是可靠的
  • "四次挥手"确认断开传输
  • TCP协议进行通信的两个应用进程:客户端、服务端。
  • 在连接中可进行大数据量的传输
  • 传输完毕,需释放已建立的连接,效率低

UDP协议: 例如视频播放,卡一下也没关系,主要得快

  • 将数据、源、目的封装成数据包,不需要建立连接
  • 每个数据报的大小限制在64K内
  • 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
  • 可以广播发送
  • 发送数据结束时无需释放资源,开销小,速度快

TCP例题

客户端Socket的工作过程包含以下四个基本的步骤:

  • 创建 Socket:根据指定服务端的 IP 地址或端口号构造 Socket 类对象。若服务器端
    响应,则建立客户端到服务器的通信线路。若连接失败,会出现异常。
  • 打开连接到 Socket 的输入/出流: 使用 getInputStream()方法获得输入流,使用
    getOutputStream()方法获得输出流,进行数据传输
  • 按照一定的协议对 Socket 进行读/写操作:通过输入流读取服务器放入线路的信息
    (但不能读取自己放入线路的信息),通过输出流将信息写入线程。
  • 关闭 Socket:断开客户端到服务器的连接,释放线路

服务器程序的工作过程包含以下四个基本的步骤

  • 调用 ServerSocket(int port) :创建一个服务器端套接字,并绑定到指定端口
    上。用于监听客户端的请求。
  • 调用 accept():监听连接请求,如果客户端请求连接,则接受连接,返回通信
    套接字对象。
  • 调用 该Socket类对象的 getOutputStream() 和 getInputStream ():获取输出
    流和输入流,开始网络数据的发送和接收。
  • 关闭ServerSocket和Socket对象:客户端访问结束,关闭通信套接字。

例子1: 客户端发送信息给服务端,服务端将数据显示在控制台上

public class TCPtest1 {
    //客户端
    @Test
    public void client(){
        Socket socket = null;//ip,服务器端的端口号
        OutputStream os = null;//流传输数据
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("127.0.0.1");//对方的ip地址
            socket = new Socket(inet,8899);
            //2.获取一个输出流,用于数据的输出
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好我是客户端mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            if (os !=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null ){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //服务端
    @Test
    public void server(){
        ServerSocket ss = null;//创建一个端口
        Socket socket = null;//接受来自客户端的操作
        InputStream is = null;//拿到流
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号,而非ip地址,因为在哪个主机上用就是哪个ip,无需指明
            ss = new ServerSocket(8899);
            //2.调用accept()表示接受来自于客户端的sockrt
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();

            //不建议这样写,可能会有乱码,因为含有中文,所占字符不一样
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = is.read(buffer)) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
            //4.读取输入流中的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer))!=-1){
                baos.write(buffer,0,len);//把内容写到ByteArrayInputStream内含的数组中,等输入完后,再把该数组内容整体翻译
            }
            System.out.println(baos.toString());//把客户端内容输出到后台
            System.out.println("收到了来自于:"+socket.getInetAddress().getHostAddress()+"的数据");//看是哪一个客户端
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

例题2: 客户端发送文件给服务端,服务端将文件保存在本地。

public class TCPTest2 {
    /*客户端*/
    @Test
    public void client(){
        Socket socket = null;//对方端口号
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            //1.造socket
            socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
            //2.获取输出流
            os = socket.getOutputStream();
            //3.获取输入流,读取数据
            fis = new FileInputStream(new File("PH.jpg"));//原件
            //4.读写过程
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer))!=-1) {
                os.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.资源关闭
            if (fis !=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*服务器端*/
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号,而非ip地址,因为在哪个主机上用就是哪个ip,无需指明
            ss = new ServerSocket(9090);
            //2.调用accept()表示接受来自于客户端的sockrt
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();
            //4.获取输出流
            fos = new FileOutputStream(new File("PH1.jpg"));//复制到的地方
            //5.写入操作
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.资源关闭
            if (fos !=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

例题3:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。并关闭相应的连接。

public class TCPTest3 {
    /*客户端*/
    @Test
    public void client(){
        Socket socket = null;//对方端口号
        OutputStream os = null;
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.造socket
            socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
            //2.获取输出流
            os = socket.getOutputStream();
            //3.获取输入流,读取数据
            fis = new FileInputStream(new File("PH.jpg"));//原件
            //4.读写过程
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer))!=-1) {
                os.write(buffer,0,len);
            }
            //关闭数据的输出,告诉服务器已输出完毕
            socket.shutdownOutput();

            //5.接收来自服务器端的数据,并显示到控制台上
            InputStream is = socket.getInputStream();
            baos = new ByteArrayOutputStream();//把数据存到内部数组
            byte[] buffer2 = new byte[20];
            int len2;
            while((len2 = is.read(buffer2))!=-1) {
                baos.write(buffer2,0,len2);
            }

            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6.资源关闭
            if (fis !=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    /*服务器端*/
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream os = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号,而非ip地址,因为在哪个主机上用就是哪个ip,无需指明
            ss = new ServerSocket(9090);
            //2.调用accept()表示接受来自于客户端的sockrt
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();
            //4.获取输出流
            fos = new FileOutputStream(new File("PH2.jpg"));//复制到的地方
            //5.写入操作
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
            System.out.println("图片传输完成");
            //6.服务器端给予客户端反馈
           os = socket.getOutputStream();
            os.write("照片已收到".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //7.资源关闭
            if (fos !=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

UDP例题

流 程:

  1. DatagramSocket与DatagramPacket

  2. 建立发送端,接收端

  3. 建立数据包

  4. 调用Socket的发送、接收方法
    发送:socket.send(packet);
    接收:socket.receive(packet);

  5. 关闭Socket

发送端与接收端是两个独立的运行程序

public class UDPTest1 {
    /*发送端*/
    @Test
    public void sender(){

        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();

            //封装一个数据包
            String str = "我是UDP发送方式的导弹";
            byte[] data = str.getBytes();
            InetAddress inet = InetAddress.getLocalHost();//写入的ip
            DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);//记录对方ip地址和端口号

            //把数据包发出去
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket!=null){
                socket.close();
            }
        }
    }
    /*接收端*/
    @Test
    public void receiver(){
        DatagramPacket packet = null;
        try {
            DatagramSocket socket = new DatagramSocket(9090);

            //数据放buffer
            byte[] buffer = new byte[100];
            packet = new DatagramPacket(buffer,0,buffer.length);

            //传输数据
            socket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(new String(packet.getData(),0,packet.getLength()));//(字节数据,长度)
    }
}

TCP与UDP区别:
TCP客户端运行的前提是服务器端也要运行
UDP则是即使接收端不允许1,发送端运行也不会报错,只是会一直开

TCP:可靠的数据传输(三次握手);进行大数据量的传输;效率低
UDP:不可靠;以数据报形式发送,数据报限定为64k;效率高

URL

URL网络编程
1.URL:统一资源定位符,对应着互联网的某一资源地址
2.格式:<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表

>  http://localhost:8080/examples/beauty.jpg?username=Tom  
>  协议    主机名   端口号 资源地址           参数列表

一个URL对象生成后,其属性是不能被改变的,但可以通过它给定的方法来获取这些属性:

public class URLTest {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.bilibili.com/video/BV1Kb411W75N?p=629&spm_id_from=pageDriver");

//            public String getProtocol(  )     获取该URL的协议名
            System.out.println(url.getProtocol());
//            public String getHost(  )           获取该URL的主机名
            System.out.println(url.getHost());
//            public String getPort(  )            获取该URL的端口号
            System.out.println(url.getPort());
//            public String getPath(  )           获取该URL的文件路径
            System.out.println(url.getPath());
//            public String getFile(  )             获取该URL的文件名
            System.out.println(url.getFile());
//            public String getQuery(   )        获取该URL的查询名
            System.out.println(url.getQuery());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

在本地搭建的网站上下载图片文件到本地

public class URLTest2 {
    public static void main(String[] args) throws IOException {
        HttpURLConnection urlConnection = null;//获取关于服务器的连接
        InputStream is = null;//创建输入流
        FileOutputStream fos = null;  //写到具体文件里
        try {
            URL url = new URL("http://localhost:8080/1.jpg");//本地
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.connect();//访问服务器,获取连接
            is = urlConnection.getInputStream();

            fos = new FileOutputStream("PH3.jpg");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
          //关闭资源
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-08-16 12:04:52  更:2021-08-16 12:06:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/17 17:04:24-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码