38.Java之IO流(常用的文件操作、IO流原理、流的分类、字节流实例、字符流实例、节点流和处理流、序列化和反序列化、对象流、标准输入输出流、转换流-字节转字符、Properties类配置文件)

38.1 文件流

文件在程序中是以流的形式来操作的

输出流
输入流
java程序-内存
文件-磁盘

:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径

38.2 常用的文件操作
创建文件对象相关构造器和方法
  1. new File(String pathname):根据路径构建一个File对象
  2. new File(File parent,String child):根据父目录文件 + 子路径构建
  3. new File(String parent,String child):根据父目录 + 子路径构建
  4. createNewFile:创建新文件
    图片来源B站韩顺平老师
    图片来源B站韩顺平老师
    图片来源B站韩顺平老师

注意:

  1. 不管是父目录还是子路径,文件夹都要存在,若父目录为空,默认是根目录,但至于在哪个盘的根目录,要根据自己电脑而言
  2. 文件的后缀不同,可以生成不同格式的文件
  3. 要添加文件名,否则创建不出文件
  1. file.getName():获取文件名字
  2. file.getAbsolutePath():获取文件绝对路径
  3. file.getParent():获取父级目录
  4. file.length():获取文件大小(字节)
  5. file.exists():判断文件是否存在
  6. file.isFile(): 判断是不是文件
  7. file.isDirectory():判断是不是目录
目录的操作和文件删除

mkdir()创建一级目录、mkdirs()创建多级目录、delete()删除空目录或文件

public void test02() {
    String directoryPath = "D:\\乱七八糟\\a\\b\\c";
    File file = new File(directoryPath);
    if (file.exists()) {
        System.out.println("存在");
    }
    else {
   //建议使用mkdirs(),mkdir()只能创建一个目录
        if (file.mkdirs()) {
            System.out.println("创建成功");
        }
        else {
            System.out.println("创建失败");
        }
    }
}
38.3 Java IO流原理
  1. I/O 是 Input/Output 的缩写,I/O 技术是非常实用的技术,用于处理数据传输。如 读/写 文件,网络通讯等
  2. Java 程序中,对于数据的输入/输出操作以 “流(stream)” 的方式进行
  3. java.io包下提供了各种 “流” 类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
  4. 输入 input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中
  5. 输出 output:将程序(内存)数据输出到磁盘、光盘等存储设备中
38.4 流的分类
  • 操作数据单位不同分为:字节流(8 bit),字符流(按字符,对应几个字节)
  • 数据流的流向不同分为:输入流,输出流
  • 流的角色的不同分为:节点流,处理流/包装流
抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter
  1. Java 的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的
  2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀

在这里插入图片描述

38.5 字节流实例
FileInputStream
public void readFile() {
        String filePath = "D:\\乱七八糟\\text\\news.txt";
        //字节数组
        byte[] buf = new byte[8];//一次读取8个字节
        int readLen = 0;
        FileInputStream fileInputStream = null;

        try {
            //创建 FileInputStream 对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            /*
            * 如果返回 -1,表示读取完毕
            * 如果读取正常,返回实际读取的字节数
            * */
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf,0,readLen));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
FileOutputStream
public void writeFile() {
    //创建 FileOutputStream 对象
    String filePath = "D:\\乱七八糟\\text\\news1.txt";
    FileOutputStream fileOutputStream = null;

    try {
        //得到 FileOutputStream 对象
        /*
        * 1. new FileOutputStream(filePath) 创建方式,当写入内容时,会覆盖原来的内容
        * 2. new FileOutputStream(filePath,true) 创建方式,当写入内容时,是追加到文件后面
        * */
        fileOutputStream = new FileOutputStream(filePath);

        //写入一个字节
        fileOutputStream.write('C');
        //写入字符串
        String str = "hello,world";
        //str.getBytes() 可以把 字符串 -> 字节数组
        fileOutputStream.write(str.getBytes());
        /*
        * write(byte() b,int off,int len)
        * 将起始位 off到指定长度 len的字节从数组写入此文件输出流
        * */
        fileOutputStream.write(str.getBytes(),0,3);
	   } catch (FileNotFoundException e) {
	       e.printStackTrace();
	   } catch (IOException e) {
	       e.printStackTrace();
	   } finally {
        //关闭资源
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
38.6 字符流实例
FileReader相关方法
  1. new FileReader(File/String)
  2. read:每次读取单个字符,返回该字符,如果到文件末尾返回 -1
  3. read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回 -1
public void readFile() {
String filePath = "D:\\乱七八糟\\text\\news.txt";
FileReader fileReader = null;
//字符数组
char[] buf = new char[8];//一次读取8个字符
int readLen = 0;

try {
    //创建 FileReader 对象,用于读取文件
    fileReader = new FileReader(filePath);
    /*
     * 如果返回 -1,表示读取完毕
     * 如果读取正常,返回实际读取到的字符数
     * */
    while ((readLen = fileReader.read(buf)) != -1) {
        System.out.print(new String(buf,0,readLen));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    //关闭文件流,释放资源
    try {
        fileReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

相关API:

  1. new String(char[]):将char[]转换成String
  2. new String(char[],off,len):将char[]的指定部分转换成String
FileWriter常用方法
  1. new FileWriter(File/String):覆盖模式,相当于流的指针在首端
  2. new FileWriter(File/String,true):追加模式,相当于流的指针在尾端
  3. write(int):写入单个字符
  4. write(char[]):写入指定数组
  5. write(char[],off,len):写入指定数组的指定部分
  6. write(string):写入整个字符串
  7. write(string,off,len):写入字符串的指定部分

相关API:String 类:toCharArray():将String转换成char[]

注意:
FileWrite使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!

public void writeFile() {
   String filePath = "D:\\乱七八糟\\text\\news2.txt";
   FileWriter fileWriter = null;
   //字符数组
   char[] chars = {'a','b','b'};
   try {
       //创建 FileWrite 对象,用于读取文件
       fileWriter = new FileWriter(filePath);//默认覆盖写入
       //写入单个字符
       fileWriter.write('H');
       //写入指定数组
       fileWriter.write(chars);
       //写入指定数组的指定部分
       fileWriter.write("小猫咪喵喵叫".toCharArray(),0,3);
       //写入整个字符串
       fileWriter.write("一起向未来");
       //写入字符串的指定部分
       fileWriter.write("北京哈尔滨",0,2);

   } catch (FileNotFoundException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   } finally {
       //关闭文件流,释放资源
       try {
           fileWriter.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
38.7 节点流和处理流

节点流 可以从一个特定的数据源读写数据
处理流 (也叫做包装流)是 “连接” 在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如 BufferedReader、BufferedWriter

节点流和处理流的区别和联系:
  1. 节点流是底层流/低级流,直接跟数据源相接
  2. 处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出
  3. 处理流对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
处理流的功能主要体现在以下两个方面:
  1. 性能的提高:主要以增加缓冲的方式来提高输入输出的效率
  2. 操作的便携:处理流可能提供了一系列便携的方法来一次输入输出大批量的数据,使用更加灵活方便
处理流-BufferedReader 和 BufferedWriter
  1. BufferedReader 和 BufferedWriter 属于字符流,是按照字符来读取数据的
  2. 关闭处理流时,只需要关闭外层流即可
BufferedReader
public void bufReader() {
  String filePath = "D:\\乱七八糟\\text\\news.txt";
   try {
       //创建 BufferedReader
       BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
       //读取
       String line = ""; //按行读取,效率高
       /* 说明
       * 1.bufferedReader.readLine() 是按行读取文件
       * 2.当返回Null时,表示文件读取完毕
       * */
       while ((line = bufferedReader.readLine()) != null) {
           System.out.println(line);
       }

       //关闭流,这里注意,只需要关闭 BufferedReader,因为底层会自动的去关闭节点流
       bufferedReader.close();

   } catch (FileNotFoundException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   }
}
BufferedWriter
public void bufWrite() {
   String filePath = "D:\\乱七八糟\\text\\news2.txt";
    try {
        /* 说明:
        * 1. new BufferedWriter(filePath,true) 表示以追加的方式写入
        * 2. new BufferedWriter(filePath) 表示以覆盖的方式写入
        * */
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("hello,world");
        bufferedWriter.newLine();//插入一个和系统相关的换行
        bufferedWriter.write("一起向未来");

        //说明:关闭外层流即可,传入的 new FileWriter(filePath),会在底层关闭
        bufferedWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

注意:
BufferedReader 和 BufferedWriter 是按照 字符 来操作的,所以不要去操作 二进制文件,可能造成文件损坏

处理流-BuffererdInputStream 和 BufferedOutputStream
图像拷贝
public void copyImg() {
   String srcFilePath = "D:\\乱七八糟\\text\\tiger.jpg";
   String destFilePath = "D:\\乱七八糟\\text\\big.jpg";

   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;

   try {
       bis = new BufferedInputStream(new FileInputStream(srcFilePath));
       bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

       //循环读取文件,并写入到 destFilePath
       byte[] buff = new byte[1024];
       int readLen = 0;
       //当返回 -1 时,就表示文件读取完毕
       while ((readLen = bis.read(buff)) != -1) {
           bos.write(buff,0,readLen);
       }
       System.out.println("文件拷贝完毕~~");
   } catch (FileNotFoundException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   } finally {
       try {
           bis.close();
           bos.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
38.8 序列化和反序列化
  1. 序列化就是在保存数据时,保存 数据的值数据类型
  2. 反序列化就是在恢复数据时,恢复 数据的值数据类型
  3. 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:
    Serializable:这是一个标记接口,没有方法
    Externalizable:该接口有方法需要实现,因此我们一般实现上面的 Serializable接口
对象流
  1. 功能:提供了对基本类型或对象类型的序列化和反序列化的方法
  2. ObjectOutputStream 提供 序列化功能
  3. ObjectInputStream 提供 反序列化功能
public void saveFile() {
  //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
   String filePath = "D:\\乱七八糟\\text\\obj.bat";

   try {
       ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

       //序列化指定数据
       oos.writeInt(100);//int -> Integer(实现了 Serializable)
       oos.writeBoolean(true);// boolean -> Boolean(实现了 Serializable)
       oos.writeChar('a');// char -> Character(实现了 Serializable)
       oos.writeDouble(9.5);// double -> Double(实现了 Serializable)
       oos.writeUTF("中国yyds");// String
       //保存一个Secrit对象
       oos.writeObject(new Secrit("旺财",10));

       oos.close();
       System.out.println("数据保存完毕(序列化形式)");
   } catch (IOException e) {
       e.printStackTrace();
   }
}

public void getFile() {
  //指定反序列化的文件
   String filePath = "D:\\乱七八糟\\text\\obj.bat";

   try {
       ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));

       //读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
       System.out.println(ois.readInt());
       System.out.println(ois.readBoolean());
       System.out.println(ois.readChar());
       System.out.println(ois.readDouble());
       System.out.println(ois.readUTF());
       Object se = ois.readObject();
       System.out.println(se);

       ois.close();
   } catch (IOException | ClassNotFoundException e) {
       e.printStackTrace();
   }
}

//如果需要序列化某个类的对象,实现 Serializable
class Secrit implements Serializable {
    private String name;
    private int age;

    public Secrit(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
注意事项和细节说明
  1. 读写顺序要一致
  2. 要求序列化或反序列化对象,需要实现 Serializable
  3. 序列化的类中建议添加 SerialVersionUID,为了提高版本的兼容性
    在这里插入图片描述
  4. 序列化对象时,默认将里面所有属性都进行序列化,但除了 static 或 transient 修饰的成员
  5. 序列化对象时,要求里面属性的类型也需要实现序列化接口
  6. 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化
38.9 标准输入输出流
类型默认设备
System.in 标准输入InputStream键盘
System.out 标准输出PrintStream显示器

在这里插入图片描述

public void file03() {
	PrintStream out = System.out;
	 //默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
	 out.print("Hello,jack");
	 //因为print底层使用的是write,所以我们可以直接调用write进行打印/输出
	 try {
	     out.write("一起向未来".getBytes());
	 } catch (IOException e) {
	     e.printStackTrace();
	 }
	 out.close();
}

public void file04() {
   String filePath = "D:\\乱七八糟\\text\\news3.txt";
    try {
    	//修改打印流输出的位置/设备
        System.setOut(new PrintStream(filePath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("hello,小猫咪");
}

public void file05() {
	String filePath = "D:\\乱七八糟\\text\\news4.txt";
	  try {
	      PrintWriter printWriter = new PrintWriter(new FileWriter(filePath));
	      printWriter.print("hi,北京北京");
	      //关闭流,才会将数据写入到文件
	      printWriter.close();
	  } catch (IOException e) {
	      e.printStackTrace();
	  }
}
38.10 转换流-字节转字符
  1. InputStreamReader:Reader的子类,可以将InputStream(字节流) 包装成 Reader(字符流)
  2. OutputStreamWriter:Writer的子类,实现将OutputStream(字节流) 包装成 Write(字符流)
  3. 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
  4. 可以在使用时指定编码格式(比如 utf-8,gbk,gb2312,ISO8859-1 等)
public void file01() {
    String filePath = "D:\\乱七八糟\\text\\news.txt";
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath),"utf-8"
        ));
        String line = "";
        //读取
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void file02() {
String filePath = "D:\\乱七八糟\\text\\news3.txt";
	 try {
	     OutputStreamWriter osw = new OutputStreamWriter(
	     		new FileOutputStream(filePath),"utf-8");
	     osw.write("一起向未来");
	     osw.close();
	 } catch (UnsupportedEncodingException e) {
	     e.printStackTrace();
	 } catch (FileNotFoundException e) {
	     e.printStackTrace();
	 } catch (IOException e) {
	     e.printStackTrace();
	 }
}
38.11 Properties类
  1. 专门用于读写配置文件的集合类
    配置文件的格式:
    键=值
    键=值
  2. 注意:键值对不需要有空格,值不需要用引号引起来。默认类型是String
Properties 的常见方法
  1. load():加载配置文件的键值对到Properties对象
  2. list():将数据显示到指定设备
  3. getProperty(Key):根据键获取值
  4. setProperty(Key,value):设置键值对到Properties对象
  5. store():将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
//使用Properties 类来读取 jdbc.properties 文件
public void readProperties() {
   //创建 Properties 对象
    Properties properties = new Properties();
    //加载指定配置文件
    try {
        properties.load(new FileReader("src\\jdbc.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    //把 k-v 显示控制台
    properties.list(System.out);
    //根据Key 获取对应的值
    String user = properties.getProperty("user");
    String pwd = properties.getProperty("password");
    System.out.println("用户名=" + user);
    System.out.println("密码 = " + pwd);
}

//使用Properties 类来创建配置文件,修改配置文件内容
public void creatProperties() {
	Properties properties = new Properties();
	 //创建
	 properties.setProperty("charset","utf8");
	 properties.setProperty("user","汤姆");//注意保存时,是中文的 unicode码值
	 properties.setProperty("pwd","abc123");
	
	 //将k-v存储文件中
	 try {
	     //null位置是生成注释
	     properties.store(new FileOutputStream("src\\mysql.properties"),null);
	 } catch (IOException e) {
	     e.printStackTrace();
	 }
	 System.out.println("保存配置文件成功");
 }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值