• 第十七章:IO流


    一、文件流:

     二、常用的文件操作:

    new File(String pathname) //根据路劲创建一个File对象

    new File(File parent, String child) //根据父目录文件+子路劲构建

    new File(String parent,String chile) //根据父目录+子路径构建

    使用createNewFile()创建新文件

    1. //方式一 new File(String pathname)
    2. @Test
    3. public void create1(){
    4. String filePath = "d:\\news3.txt";
    5. File file = new File(filePath);
    6. try {
    7. file.createNewFile();
    8. } catch (IOException e) {
    9. e.printStackTrace();
    10. }
    11. System.out.println("创建成功");
    12. }
    13. //方式二 new File(File parent, String child)
    14. @Test
    15. public void create2(){
    16. File parentFile = new File("e:\\");
    17. String fileName= "news.txt";
    18. File file = new File(parentFile,fileName);
    19. try {
    20. file.createNewFile();
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }
    24. }
    25. //方法三 new File(String parent,String chile)
    26. @Test
    27. public void create3(){
    28. String parentPath = "e:\\";
    29. String fileName = "news3.txt";
    30. File file = new File(parentPath,fileName);
    31. try {
    32. file.createNewFile();
    33. } catch (IOException e) {
    34. e.printStackTrace();
    35. }
    36. }

    三、获取文件信息

    1. @Test
    2. public void info(){
    3. //先创建文件对象
    4. File file = new File("d:\\news.txt");
    5. //调用相应的方法,得到对应的信息
    6. System.out.println("文件名字:"+file.getName());
    7. System.out.println("获取文件绝对路劲:"+file.getAbsolutePath());
    8. System.out.println("获取父级目录"+file.getParent());
    9. System.out.println("获取文件大小(字节):"+file.length());
    10. System.out.println("判断文件是否存在:"+file.exists());
    11. System.out.println("是不是一个文件:"+file.isFile());
    12. System.out.println("是不是一个目录:"+file.isDirectory());
    13. }

    四、目录的操作

    1. @Test
    2. public void m1() {
    3. //判断文件是否存在,存在就删除
    4. String filePath = "d:\\news1.txt";
    5. File file = new File(filePath);
    6. if (file.exists()) {
    7. if (file.delete()) {
    8. System.out.println("删除成功");
    9. } else {
    10. System.out.println("删除失败");
    11. }
    12. } else {
    13. System.out.println("该文件不存在");
    14. }
    15. }
    16. @Test
    17. public void m2() {
    18. //判断文件目录,存在就删除 , 在java中,目录也被当成文件
    19. String filePath = "d:\\demo";
    20. File file = new File(filePath);
    21. if (file.exists()) {
    22. if (file.delete()) {
    23. System.out.println("删除成功");
    24. } else {
    25. System.out.println("删除失败");
    26. }
    27. } else {
    28. System.out.println("该目录不存在");
    29. }
    30. }
    31. @Test
    32. public void m3() {
    33. //判断文件目录是否存在,不存在就创建
    34. String filePath = "d:\\demo";
    35. File file = new File(filePath);
    36. if (file.exists()) {
    37. System.out.println("该目录不存在");
    38. } else {
    39. if (file.mkdir()) { //创建多级目录使用 mkdirs
    40. System.out.println("创建成功");
    41. }else{
    42. System.out.println("创建失败");
    43. }
    44. }
    45. }

    五、IO的原理与分类

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

    输出output:将程序(内存) 数据输出到磁盘、光盘等存储设备中

    按操作数据单位不同分为:字节流(8 bit) 二进制文件字符流(按字符)文本文件

    抽象基类                        字节流                        字符流

    输入流                        InputStream                  Reader

    输出流                        OutputStream               Writer

    六、字节流

    (1)FileInputStream (外面的文件到程序):

    1. @Test
    2. public void readFile01() {
    3. String filePah = "d:\\news123.txt";
    4. int readData = 0;
    5. FileInputStream fileInputStream = null;
    6. try {
    7. //创建 FileInputStream 对象 用于读取 文件
    8. fileInputStream = new FileInputStream(filePah);
    9. //返回-1,表示读取完毕
    10. while ((readData = fileInputStream.read()) != -1) {
    11. System.out.print((char) readData); //转成char显示
    12. }
    13. } catch (IOException e) {
    14. e.printStackTrace();
    15. } finally {
    16. //关闭文件流,释放资源
    17. try {
    18. fileInputStream.close();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    24. /**
    25. * 演示读取文件。。。
    26. * 单个字节的读取,效率比较低
    27. * ->使用read(byte[] b ) 读取提高效率
    28. * new String(buf,0,buf.length) 第一个参数为char数组,第二个参数开始位置,第三个参数为结束位置
    29. */
    30. @Test
    31. public void readFile02() {
    32. String filePah = "d:\\news123.txt";
    33. int readLen = 0;
    34. //定义字节数组
    35. byte[] buf = new byte[8]; //一次读取8个字节
    36. FileInputStream fileInputStream = null;
    37. try {
    38. //创建 FileInputStream 对象 用于读取 文件
    39. fileInputStream = new FileInputStream(filePah);
    40. //返回-1,表示读取完毕
    41. while ((readLen = fileInputStream.read(buf)) != -1) {
    42. System.out.println(new String(buf,0,buf.length));
    43. }
    44. } catch (IOException e) {
    45. e.printStackTrace();
    46. } finally {
    47. //关闭文件流,释放资源
    48. try {
    49. fileInputStream.close();
    50. } catch (IOException e) {
    51. e.printStackTrace();
    52. }
    53. }
    54. }

    (2)FileOutputStream(程序写到外部文件):

    注意:如果写的文件不存在它会自动创建

    1. /**
    2. * 演示OutputStream 将数据写道文件中
    3. * 如果该文件不存在,则创建
    4. */
    5. @Test
    6. public void writeFile(){
    7. //创建FileOutputStream对象
    8. String filePath = "d:\\news123.txt";
    9. FileOutputStream fileOutputStream = null;
    10. try {
    11. //new FileOutputStream(filePath); 会覆盖原来的内容
    12. //new FileOutputStream(filePath,true); 创建方式时追加到文件后面
    13. fileOutputStream = new FileOutputStream(filePath,true);
    14. //写入一个字节
    15. // fileOutputStream.write('H');//写入一个a试试
    16. //写入字符串
    17. String str = "hello,world";
    18. // //str.getByes转化为字符数组
    19. // fileOutputStream.write(str.getBytes()); //方法一
    20. fileOutputStream.write(str.getBytes(),0,str.length());
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }finally {
    24. try {
    25. fileOutputStream.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }

    (3)案例文件拷贝:

    1. @SuppressWarnings({"all"}) //取消文件警告
    2. public class Hello {
    3. public static void main(String[] args) {
    4. String oldFilePah = "d:\\avatar.jpg";
    5. String newFilePah = "d:\\avatar(1).jpg";
    6. int readLen = 0;
    7. byte[] buf = new byte[1024];
    8. FileOutputStream fileOutputStream = null;
    9. FileInputStream fileInputStream = null;
    10. try {
    11. fileInputStream = new FileInputStream(oldFilePah);
    12. fileOutputStream = new FileOutputStream(newFilePah);
    13. while ((readLen = fileInputStream.read(buf)) != -1){
    14. fileOutputStream.write(buf,0, readLen);
    15. }
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. } finally {
    19. try {
    20. fileInputStream.close();
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }
    24. try {
    25. fileOutputStream.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }
    31. }

    七、字符流

    (1)FileReader(读取文件字符流到程序):

    1. @Test
    2. /**
    3. * 单个字符读取
    4. */
    5. public void readFile1(){
    6. String filePath = "d:\\news123.txt";
    7. int data = ' ';
    8. FileReader fileReader = null;
    9. try {
    10. fileReader = new FileReader(filePath);
    11. while ((data = fileReader.read()) != -1){
    12. System.out.print((char) data);
    13. }
    14. } catch (IOException e) {
    15. e.printStackTrace();
    16. } finally {
    17. try {
    18. fileReader.close();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    24. @Test
    25. /**
    26. * 多个字符的读取
    27. */
    28. public void readFile2(){
    29. String filePath = "d:\\news123.txt";
    30. char[] buf = new char[8];
    31. int readLen = 0;
    32. FileReader fileReader = null;
    33. try {
    34. fileReader = new FileReader(filePath);
    35. //循环读取 使用read(buf),返回的时实际读取到的字符数
    36. //如果返回-1,说明文件结束
    37. while ((readLen = fileReader.read(buf)) != -1){
    38. System.out.print(new String(buf,0,readLen));
    39. }
    40. } catch (IOException e) {
    41. e.printStackTrace();
    42. } finally {
    43. try {
    44. fileReader.close();
    45. } catch (IOException e) {
    46. e.printStackTrace();
    47. }
    48. }
    49. }

    (2)FileWriter(读取程序字符流到文件):

    注意:new FileWriter(File/String,true) //表示追加    new FileWriter(File/String) //表示覆盖

    1. @Test
    2. public void writeFile(){
    3. String filePath = "d:\\news123.txt";
    4. String str = "风雨之后,定见彩虹";
    5. FileWriter fileWriter = null;
    6. try {
    7. fileWriter = new FileWriter(filePath); //直接覆盖
    8. fileWriter = new FileWriter(filePath,true); //追加
    9. fileWriter.write(str,0,str.length());
    10. //在数量大的时候使用循环
    11. } catch (IOException e) {
    12. e.printStackTrace();
    13. } finally {
    14. try {
    15. fileWriter.close();
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. }

    八、处理流

    (1)BufferReader(读取文件到程序):

    1. public static void main(String[] args) throws IOException {
    2. String filePath = "d:\\news123.txt";
    3. //创建bufferedReader
    4. BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
    5. //读取
    6. String line;// bufferedReader.readLine(); 按行读取效率高
    7. //当返回null的时候表示读取完毕
    8. while ((line = bufferedReader.readLine())!= null){
    9. System.out.print(line);
    10. }
    11. //关闭流,只需要关闭外层流
    12. bufferedReader.close();
    13. }

     (2) BufferWriter(读取程序到文件):

    1. public static void main(String[] args) throws IOException {
    2. String filePath = "d:\\news123.txt";
    3. //创建BufferedWriter FileWriter(filePath) ,第二个参数表示是否追加
    4. BufferedWriter bufferedWriter= new BufferedWriter(new FileWriter(filePath));
    5. bufferedWriter.write("hello,张三");
    6. bufferedWriter.newLine();//插入一个换行符
    7. bufferedWriter.close();
    8. }

    (3)案例文件的拷贝:

    1. //文件的拷贝
    2. public static void main(String[] args) throws IOException {
    3. String filePath = "d:\\news123.txt";
    4. String filePath2 = "d:\\news456.txt";
    5. String line;
    6. BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
    7. BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath2));
    8. while ((line = bufferedReader.readLine()) != null){
    9. bufferedWriter.write(line);
    10. }
    11. bufferedReader.close();
    12. bufferedWriter.close();
    13. }

    (4)BufferedOutputSream字节处理流(程序写到文件):

    (5)BuffereInputStream字节处理流(文件到程序):

    1. //文件的拷贝
    2. //字节流可以操作二进制文件(图片,视频),可以操作文本文件
    3. public static void main(String[] args) throws IOException {
    4. String filePath = "d:\\news123.txt";
    5. String filePath2 = "d:\\news456.txt";
    6. BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
    7. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath2));
    8. byte[] buff = new byte[1024];
    9. int readLen = 0;
    10. while ((readLen = bufferedInputStream.read(buff)) != -1){
    11. bufferedOutputStream.write(buff,0,readLen);
    12. }
    13. bufferedInputStream.close();
    14. bufferedOutputStream.close();
    15. }

    (6)ObjectOutputStream(程序到文件):序列化到文件

    序列化和反序列化:序列化就是在保存数据时,保存数据的值和数据类型。反序列化就是在恢复数据时,恢复数据的值和数据类型。要支持序列化需要实现Serializable//标记接口(用这个)  Externailzable(这恶鬼不常用)

    1. public static void main(String[] args) throws IOException {
    2. //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
    3. String filePath = "d:\\news12.dat";
    4. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
    5. //序列化数据到 d:\\news12.dat
    6. oos.write(100); //int --- Integer (实现 serializable)
    7. oos.writeBoolean(true); //boolean -- Boolean(实现 serializable)
    8. oos.writeDouble(100.9); //double -- Double (实现 serializable)
    9. oos.writeUTF("韩顺平教育"); //String
    10. oos.close();
    11. System.out.println("序列化完成");
    12. }

    (7)ObjectInputStream(文件到程序):反序列化到程序

    1. public static void main(String[] args) throws IOException {
    2. //指定反序列化的文件
    3. String filePath = "d:\\news12.dat";
    4. ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
    5. //反序列化,读取的顺序要和保存数据的顺序一致。否则会报异常
    6. System.out.println(ois.readInt());
    7. System.out.println(ois.readBoolean());
    8. System.out.println(ois.readDouble());
    9. System.out.println(ois.readUTF());
    10. }

    (8)标准输入输出流:

    system.out.print()   system.in

    九、转换流

    当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文乱码,所以建议将字节流转换成字符流。在使用时可以指定编码

    (1)InputStreamReader(文件读取到程序):

    1. public static void main(String[] args) throws IOException {
    2. String filePath = "d:\\news123.txt";
    3. //1.把FileInputStream 转成 InputStreamReader
    4. //2.指定编码 gdk
    5. InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath),"gbk");
    6. //3.把 InputStreamReader 传入 BufferedReader(isr)
    7. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    8. //4.读取
    9. String s = bufferedReader.readLine();
    10. System.out.println("读取到的是:" + s);
    11. ///5.关闭外层
    12. bufferedReader.close();
    13. }

    (2)OutputStreamWriter(程序到文件):

    1. public static void main(String[] args) throws IOException {
    2. String filePath = "d:\\news123.txt";
    3. OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
    4. outputStreamWriter.write("hi,韩顺平教育");
    5. outputStreamWriter.close();
    6. }

    十、Properties类

    1. load:加载配置文件的键值对到Properties对象
    2. list:将数据显示到指定设备
    3. getProperty(key):根据键获取值
    4. setProperty(key,value):根据键值对到Properies对象
    5. store:将Properties中的键值对存储到配置文件,在Idea中,保存信息到配置文件,如果含有中文,会存储为unicode码

    (1)Properties读取文件:

    1. public static void main(String[] args) throws IOException {
    2. //使用Properies 类来读取配置文件
    3. //1.创建Properies对象
    4. Properties properties = new Properties();
    5. //2.加载指定文件
    6. properties.load(new FileReader("d:\\news123.txt"));
    7. //3.把k-v显示在控制台
    8. properties.list(System.out);
    9. //4.根据key 获取对应的值
    10. String id = properties.getProperty("id");
    11. String name = properties.getProperty("name");
    12. System.out.println("id:"+id+" name:"+name);
    13. }

    (2)Properties修改文件:

    1. public static void main(String[] args) throws IOException {
    2. //使用Properies 类来创建配置文件,修改配置文件
    3. Properties properties = new Properties();
    4. //创建
    5. //如果该文件没有key,就是创建
    6. //如果该文件右key,就是修改
    7. properties.setProperty("charset","utf8");
    8. properties.setProperty("user","root");
    9. properties.setProperty("psw","root");
    10. //将k-v存储文件 null表示unicode码
    11. properties.store(new FileOutputStream("d:\\news123.txt"),null);
    12. }

    十一、课后作业

    1. public static void main(String[] args) throws IOException {
    2. String dirctory = "d:\\mytemp";
    3. File file = new File(dirctory);
    4. if (!file.exists()){
    5. if (file.mkdir()){
    6. System.out.println("创建成功");
    7. }else{
    8. System.out.println("创建失败");
    9. }
    10. }
    11. String filePath = dirctory+"\\hello.txt";
    12. File file1 = new File(filePath);
    13. if (!file1.exists()){
    14. if (file1.createNewFile()){
    15. System.out.println("创建成功");
    16. }else{
    17. System.out.println("创建失败");
    18. }
    19. }
    20. }

    1. public static void main(String[] args) throws IOException {
    2. String filePath = "d:\\news123.txt";
    3. BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
    4. String str = "";
    5. int i = 0;
    6. while((str = bufferedReader.readLine()) != null) {
    7. i++;
    8. System.out.println(i + ". " + str);
    9. }
    10. }

    1. @SuppressWarnings({"all"}) //取消文件警告
    2. public class Hello {
    3. public static void main(String[] args) throws IOException {
    4. String filePath = "d:\\news123.txt";
    5. Properties properties = new Properties();
    6. properties.load(new FileInputStream(filePath));
    7. String name = properties.getProperty("name");
    8. String color = properties.getProperty("color");
    9. int age = Integer.parseInt(properties.getProperty("age"));
    10. Dog dog = new Dog(name, color, age);
    11. System.out.println(dog);
    12. ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
    13. objectOutputStream.writeObject(dog);
    14. objectOutputStream.close();
    15. }
    16. }
    17. class Dog implements Serializable{
    18. String name;
    19. String color;
    20. int age;
    21. public Dog(String name, String color, int age) {
    22. this.name = name;
    23. this.color = color;
    24. this.age = age;
    25. }
    26. @Override
    27. public String toString() {
    28. return "Dog{" +
    29. "name='" + name + '\'' +
    30. ", color='" + color + '\'' +
    31. ", age=" + age +
    32. '}';
    33. }
    34. }

     

  • 相关阅读:
    二十三种设计模式全面解析-工厂模式:创造对象的魔法工厂
    D. Ball-(CDQ分治)
    CSDN每日一题学习训练——Java版(克隆图、最接近的三数之和、求公式的值)
    pytorch数学操作
    Python中的三个基本知识点
    教你如何帮助孩子做好时间管理,不再需要重复提醒!
    玩转webpack(01):初识webpack
    Mybatis 使用参数时$与#的区别
    以业务为核心,泛微协助生产制造企业推动销售到生产一体化管理
    vue3中使用vue-echarts
  • 原文地址:https://blog.csdn.net/m0_61927991/article/details/127091685