zoukankan      html  css  js  c++  java
  • 使用IOUtils和FileUtils

    文本输出应该比较常用,以前都是通过反复的创建InputStream, InputReader, OutputStream, OutputWriter等去输入输出文本,比较麻烦。

    Apache提供了一个commons-io.jar包,里面有很多IO相关的工具,比如输入输出文本等,着实方便了很多。

    比如读取一个文件:

     

    Java代码  收藏代码
    1. // by FileUtils  
    2. List<String> lines = FileUtils.readLines(file, "UTF-8");  
    3.   
    4. // by IOUtils  
    5. List<String> lines = IOUtils.readLines(new FileInputStream(file), "UTF-8");  

     

     

    写入文件:

     

    Java代码  收藏代码
    1. // by FileUtils  
    2. FileUtils.writeLines(file, "UTF-8", lines);  
    3.   
    4. // by IOUtils  
    5. IOUtils.writeLines(lines, nullnew FileOutputStream(file));  
     

     

    FileUtils/IOUtils还有其他很多方法用于读取写入文件,或者读取输出到InputStream/OutputStream等,这里就不再一一列举,可以参考查阅对应的Java Doc

    FileUtils: http://commons.apache.org/io/api-2.0/org/apache/commons/io/FileUtils.html

    IOUtils: http://commons.apache.org/io/api-2.0/org/apache/commons/io/IOUtils.html

     

    特殊需求:FileUtils/IOUtils中写入文本的方法看上去都是只能一次性的批量写入多行,并覆盖原有的文本,如果我们需要单行写入怎么办呢,其实在IOUtils中是提供了这样的方法的,只不过比较隐晦而已:

    Java代码  收藏代码
    1. try {  
    2.     OutputStream os = new FileOutputStream(file, true);  
    3.     IOUtils.writeLines(lines, null, os, "UTF-8");  
    4. catch (IOException e) {  
    5.     e.printStackTrace();  
    6. }  

    其实就是在初始化FileOutputStream的时候 ,第二个参数append设为true就可以了。

  • 相关阅读:
    RAID实战案例
    文件系统常用工具实战篇
    挂载文件系统
    硬盘结构类型概述
    创建文件系统实战篇
    JumpServer的会话管理及命令过滤器应用案例
    JumpServer的权限管理
    JumpServer的用户管理
    helm基础
    hpa控制器
  • 原文地址:https://www.cnblogs.com/chenying99/p/2644875.html
Copyright © 2011-2022 走看看