zoukankan      html  css  js  c++  java
  • java IO 学习(二)

    文件表示形式的转换:

    一、从系统文件变成java中可以使用的文件对象

      File file = new FIle("文件的路径");

    二、读取文件系统中文件的原始字节流,要读取字符流,请考虑使用 FileReader (File 转 InputStream

      FileInputStream fis = new FileInputStream(file);

    三、创建一个文件输出流,用于写入原始字节流

      FileOutputStream fos = new FileOutputStream(file);

    四、将一个输入流其中的数据写入到一个byte数组中(InputStream 转 byte[]

      方法一:

      FileInputStream fis = new FileInputStream(file);

      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

      byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据 

      int rc = 0; 

      while ((rc = fis.read(buff, 0, 100)) > 0) { 

        baos.write(buff, 0, rc); 

      } 

      byte[] in_b = baos.toByteArray(); // in_b为转换之后的结果 

      方法二:

      FileInputStream fis = new FileInputStream(file);

      byte[] buff = new byte[fis.available()]; 

      fis.read(buff);// read方法返回一个int值,并且把fis读取到的数据保存到buff数组中

      

    五、byte[]转换成InputStream

      ByteArrayInputStream bais = new ByteArrayInputStream(byte[] buf);

    六、根据byte数组,生成文件

      File file = new File(""); // 新建一个File

      OutputStream output = new FileOutputStream(file);// 转成OutputStream 形式

      BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);// 转成BufferedOutputStream 

      bufferedOutput.write(byt);// 把byte[]写入BufferedOutputStream 

    注意有些语句可能会抛出异常,注意流要记得关闭

      

  • 相关阅读:
    2019.10.07题解
    2019.10.06题解
    2019.10.05'题解
    2019.10.05题解
    java邮件发送
    注释类型 XmlType
    Spring 注解
    @SuppressWarnings(unchecked)作用解释
    vm文件
    Apache Shiro 使用手册(一)Shiro架构介绍
  • 原文地址:https://www.cnblogs.com/qq765065332/p/8744092.html
Copyright © 2011-2022 走看看