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 

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

      

  • 相关阅读:
    15年双11手淘前端技术分享(转)
    高程第9章 客户端检测
    高程8.4 screen对象 8.5history对象 8.6小结
    高程8.2location对象 8.3navigator对象
    高程第8章 BOM 8.1window对象
    高程 7.3 模仿块级作用域 7.4私有变量 7.5小结
    高程 第7章函数表达式 7.1递归 7.2闭包
    23、GoAccess分析Nginx日志
    11、Nginx反向代理服务
    10、LNMP架构
  • 原文地址:https://www.cnblogs.com/qq765065332/p/8744092.html
Copyright © 2011-2022 走看看