zoukankan      html  css  js  c++  java
  • Java IO流的读写操作(掌握)

    输入输出流

     字节输入流 FileInputStream

    /**
          * 标准 读取流
          */
         public static void test2() {
              
              File file = new File("test.txt");
              
              //创建 输入流
              InputStream is = null;
              try {
                  //获取字节流
                  is = new FileInputStream(file);
                  int temp;//定义 接受每次 读取的 长度
                  //循环 判断 为-1停止
                  while ((temp = is.read()) != -1) {
                       //打印
                       System.out.print((char) temp);
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  try {
                       if (is != null) {
                            //非空关闭资源
                            is.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }
    /**
    * 批量 输入流读取 */ public static void test1() { // 创建源 File file = new File("test.txt"); InputStream is = null; // 创建输入流 try { is = new FileInputStream(file); // 读取 byte[] flush = new byte[10]; // 定义读取的缓冲容器 int len = -1; // 接受每次读取的长度 while ((len = is.read(flush)) != -1) { // 字节数 到 字符串 解码 ,每次在 容器 arr数组中 读取 0 到 len的长度. String str = new String(flush, 0, len); System.out.print(str); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { // 非空关闭资源 is.close(); } } catch (Exception e2) { e2.printStackTrace(); } } }

     

    字节输出流 FileIOutputStream

       /**
          * 批量 输出流读取
          */
         public static void test1() {
    //         1.创建源文件
              File file = new File("text1.txt");
    //         2.创建输出流
              OutputStream os = null;
              try {
    //             3.操作流
                  os = new FileOutputStream(file, true);//  true在后面追加内容
                  String str = "IO is so easy!
    ";
                  byte[] bytes = str.getBytes(); //字符串到  字节数组  编码
                  // 写入 字节从0 到该字节数组的长度
                  os.write(bytes, 0, bytes.length);
                  // 刷新
                  os.flush();
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  try {
    //                  4.释放资源
                       if (os != null) {
                            os.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }

    字节流对文件的Copy

    /**
          *
          * @param srcPath 要复制的文件路径
          * @param destPath 复制到该文件中的路径
          */
         public static void copy(String srcPath, String  destPath) {
    //         1.创建源文件
              File file = new File(srcPath); // 要复制的文件
              File dest = new File(destPath); // 复制到该文件中
    //         2.创建输出流
              InputStream is = null;
              OutputStream os = null;
              try {
    //             3.操作流
                  // 输入流
                  is = new FileInputStream(file);
                  // 输出流
                  os = new FileOutputStream(dest);// true在后面追加内容
                  int len = 0;// 定义接受每次读取的文件长度
                  byte[] flush = new byte[10];// 读取缓冲器
                  while ((len = is.read(flush)) != -1) {
                       // 写入到该文件
                       os.write(flush, 0, len);
                  }
                  // 刷新
                  os.flush();
                  System.out.println("复制完毕");
              } catch (Exception e) {
                  System.out.println("复制失败");
                  e.printStackTrace();
              } finally {
                  try {
    //                  4.释放资源
                       if (os != null) {
                            os.close();
                       }
                       if (is != null) {
                            is.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }

    字符流对的文件copy的操作

        /**
          * 字符输出流
          */
         public static void test2() {
              File file = new File("dest1.txt");
              Writer fw = null;
              try {
                  fw = new FileWriter(file);
                  String str = "大家好,我是康纳
    哈哈";
                  // 写法 1
    //            char[] charArray = str.toCharArray(); //字符串到 字节数组
    //            fw.write(charArray, 0, charArray.length);
                  // 写法 2
    //            fw.write(str);
                  // 写法3
                  fw.append("IO is so easy
     ").append("大家好我是康纳郭");
                  fw.flush();
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  try {
                       if (fw != null) {
                            fw.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }
         /**
          * 字符输入流
          */
         public static void test1() {
              File file = new File("test.txt");
              // 字符输入流
              Reader fr = null;
              try {
                  fr = new FileReader(file);
                  // 操作缓冲区
                  char[] flush = new char[10];
                  // 每次接受字符长度
                  int len = -1;
                  while ((len = fr.read(flush)) != -1) {
                       // 字符数组 到字符串
                       String str = new String(flush, 0,  len);
                       System.out.print(str);
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  try {
                       // 关流
                       if (fr != null) {
                            fr.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }
         /**
          * 字符流 文件的拷贝
          *
          * @param srcPath  要复制的文件
          * @param destPath 复制到该文件中
          */
         public static void copy(String srcPath, String  destPath) {
              // 创建源
              File src = new File(srcPath);
              File dest = new File(destPath);
              // 创建字符流
              Reader reader = null;
              Writer writer = null;
              try {
                  reader = new FileReader(src);
                  writer = new FileWriter(dest);
                  int len = -1;// 每次读取的长度
                  char[] flush = new char[2];// 缓冲器
    //            int i = 0;
                  while ((len = reader.read(flush)) != -1) {
    //                 writer.write(i+" ");
                       writer.write(flush, 0, len);
    //                 writer.write("
    ");
                  }
                  writer.flush();// 刷新
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  // 关流
                  try {
                       if (writer != null) {
                            writer.close();
                       }
                       if (reader != null) {
                            reader.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }

    字节数组流

    字节数组输入流 ByteArrayInputStream

     /**
          * 字节数组输出流
          *
          * 创建源:内部维护
          * 选择流:不关联源
          * 操作:
          * 释放资源:不做处理
          */
         public static void byteArrayOutPut() {
              String str = "talk is cheap show me the code";
              
              byte arr [] =null;//用来接收读取的字节数组
              
              ByteArrayOutputStream baos = null;//使用子类特有的方法。不发生多态
              try {
                  baos = new ByteArrayOutputStream();
                  
                  byte[] bytes = str.getBytes();// 字符串  ---->字节数组 编码
                  //读取
                  baos.write(bytes,0,bytes.length);
                  //刷新
                  baos.flush();
                  
                  //返回读取的字节数组
                  arr = baos.toByteArray();
                  
                  System.out.println(arr.length);
                  System.out.println(new  String(arr,0,baos.size()));
              } catch (Exception e) {
                  e.printStackTrace();
              }
         }

    文件的copy,对接流。图片读取字节数组中,字节数组写出到图片。

       /**
          * 图片转换 到 字节数组
          *   1. 图片到程序 FileInputStream
          *   2. 程序到字节数组: ByteArrayOutputStream
          */
         public static byte[] FileToBtyeArryay(String src) {
              // 创建源
              File file = new File(src);
              InputStream is = null;
              ByteArrayOutputStream baos = null;
              // 创建输入流
              try {
                  is = new FileInputStream(file);
                  baos = new ByteArrayOutputStream();
                  // 读取
                  byte[] flush = new byte[1024 * 10]; // 定义读取的缓冲容器
                  int len = -1; // 接受每次读取的长度
                  while ((len = is.read(flush)) != -1) {
                       baos.write(flush, 0, len); // 写入到字节数组
                  }
                  baos.flush();
                  // 返回读取的字节数组
                  return baos.toByteArray();
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  try {
                       if (is != null) {
                            // 非空关闭资源
                            is.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
              return null;
         }
         /**
          * 字节数组转换到图片
          * 1.字节数组读取到程序  ByteArrayInpuStream
          *
          * 2.程序写出到文件 FileOutPutStream
          */
         public static void ByteArrayToFile(byte[] src,  String filePath) {
              //要读取到的文件路径
              File file = new File(filePath);
              //字节输入流
              InputStream bais = null;
              //文件输出流
              OutputStream os = null;
              try {
                  bais = new ByteArrayInputStream(src);
                  os = new FileOutputStream(file);
                  
                  int len = -1;
                  byte[] flush = new byte[1024 * 2];
                  while ((len = bais.read(flush)) != -1)  {//读取字节数组流
                       os.write(flush, 0, len);//写入到文件
                  }
                  os.flush();
              } catch (Exception e) {
                  e.printStackTrace();
              }finally {
                  try {
                       if(os!= null) {
                            os.close();
                       }
                  } catch (Exception e2) {
                       e2.printStackTrace();
                  }
              }
         }

    重点

    字节缓冲流

    /**
          *
          *  加入 字节缓冲流
          * @param srcPath  要复制的文件路径
          * @param destPath 复制到该文件中的路径
          */
         public static void copy(String srcPath, String  destPath) {
    //         1.创建源文件
              File file = new File(srcPath); // 要复制的文件
              File dest = new File(destPath); // 复制到该文件中
    //         2.创建输出流
              // jdk1.7 try可自动关闭资源
              //加上字节缓冲流
              try (InputStream is =  new  BufferedInputStream(new FileInputStream(file));
                       OutputStream os = new  BufferedOutputStream(new FileOutputStream(dest))) {
                  int len = 0;// 定义接受每次读取的文件长度
                  byte[] flush = new byte[1024];// 读取缓冲器
                  while ((len = is.read(flush)) != -1) {
                       // 写入到该文件
                       os.write(flush, 0, len);
                  }
                  // 刷新
                  os.flush();
                  System.out.println("复制完毕");
              } catch (Exception e) {
                  System.out.println("复制失败");
                  e.printStackTrace();
              }
         }

    字符缓冲流

    /**
          * 字符流 文件的拷贝+字符缓冲流
          *
          * @param srcPath  要复制的文件
          * @param destPath 复制到该文件中
          */
         public static void copy(String srcPath, String  destPath) {
              // 创建源
              File src = new File(srcPath);
              File dest = new File(destPath);
              //缓冲流
              try (BufferedReader br = new BufferedReader(new  FileReader(src));
                       BufferedWriter bw = new  BufferedWriter(new FileWriter(dest))) {
                  //一次读一行
                  String line = null;
                  while ((line = br.readLine()) != null) {
                       bw.write(line);
                       bw.newLine();//换行
                  }
                  bw.flush();// 刷新
              } catch (Exception e) {
                  e.printStackTrace();
              }
         }

    工具类的CommonsIO使用

    FileUtils:工具类

    //文件大小
              long sizeOf = FileUtils.sizeOf(new  File("src/com/gskj/commons/CommonsTest01.java"));
              System.out.println(sizeOf);
              //目录大小
              sizeOf = FileUtils.sizeOf(new  File("D:\software\JavaWebTools\SpringEclipse-workspace\IO_Study03"));
              System.out.println(sizeOf);
    
    
    //打印子孙级目录
              Collection<File> listFiles =  FileUtils.listFiles(
                       new  File("D:/software/JavaWebTools/SpringEclipse-workspace/IO_Study03")
                       ,  EmptyFileFilter.NOT_EMPTY,DirectoryFileFilter.INSTANCE );
    //        for (File file : listFiles) {
    //            System.out.println(file.getAbsolutePath());
    //        }
              
              //文件过滤
              //文件后缀为 .java
              Collection<File> listFiles2 =  FileUtils.listFiles(
                       new  File("D:/software/JavaWebTools/SpringEclipse-workspace/IO_Study03")
                       , new  SuffixFileFilter("java"),DirectoryFileFilter.INSTANCE );
    //        for (File file : listFiles2) {
    //            System.out.println(file.getAbsolutePath());
    //        }
              
              //文件后缀为 .java .class
              Collection<File> listFiles3 =  FileUtils.listFiles(
                       new  File("D:/software/JavaWebTools/SpringEclipse-workspace/IO_Study03")
                       , FileFilterUtils.or(new  SuffixFileFilter("java"),new  SuffixFileFilter("class")),DirectoryFileFilter.INSTANCE  );
              for (File file : listFiles3) {
                  System.out.println(file.getAbsolutePath());
              }
    
    
    //从文件中读取内容
              String msg = FileUtils.readFileToString(new  File("commons.txt"),"utf-8");
              System.out.println(msg);
              
              //逐行读取
              List<String> readLines = FileUtils.readLines(new  File("commons.txt"),"utf-8");
              for (String string : readLines) {
                  System.out.println(string);
              }
    
    
    //将指定类型的内容写出
              FileUtils.write(new File("write.txt"),"安徽山东i啊回到i傻傻的
    ","utf-8");
              
              FileUtils.writeStringToFile(new  File("write.txt"), "安徽山东i啊回到i傻傻的
    ",  "utf-8",true);
              
              FileUtils.writeByteArrayToFile(new  File("write.txt"), "安徽山东i啊回到i傻傻的".getBytes("utf-8"),true);
    
    
    //复制文件
              //FileUtils.copyFile(new File("gtaf2.jpg"), new  File("gtaf2_1.jpg"));
              //复制文件到目录
              //FileUtils.copyFileToDirectory(new  File("gtaf2.jpg"), new File("lib"));
              
              //copy URL内容
              String url  ="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1585912570744&di=bd41c4491cb14ed82a5e3bb0f2ceb78c&imgtype=0&src=http%3A%2F%2Fa4.att.hudong.com%2F21%2F09%2F01200000026352136359091694357.jpg";
              FileUtils.copyURLToFile(new URL(url ), new  File("copy.jpg"));
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    白盒,单元测试
    向数据库添加100W 条数据 性能测试
    软件测试
    软件需求工程-产品经理该如何更好地记录反馈、捕捉需求?
    Spring,Spring MVC,MyBatis,Hibernate总结
    Java基础总结
    Java8新特性_四大内置核心函数式接口
    Lambda表达式及相关练习
    Java 8新特性(Lambda,Stream API)
  • 原文地址:https://www.cnblogs.com/mt-blog/p/13332148.html
Copyright © 2011-2022 走看看