zoukankan      html  css  js  c++  java
  • [Java I/O] TextFile 工具类

    一种常见的编程任务是,从一个文件读取内容,修改内容,再把内容写到另一个文件里。 Java 要实现读取、写入操作,需要创建多个类才能产生一个 Stream 进行操作。

    下面是一个简单的工具类,封装对文件的读、写操作,提供简洁的接口。

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class TextFile {
    
        /**
         * 
         * @param fileName The full path of the target file
         * @return
         */
        public static String read(String fileName){
            
            StringBuilder sb = new StringBuilder();
            
            try {
                BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile()));
                
                String s;
                try {
                    while( (s = in.readLine()) != null ){
                        sb.append(s);
                        sb.append("
    ");
                    }
                }finally{
                    in.close();
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            return sb.toString();
        }
        
        /**
         * 
         * @param fileName The full path of the target file 
         * @param text The content which is written to the target file
         */
        public static void write(String fileName, String text){
            try {
                PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
                out.print(text);
                out.close();            
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    TextFile 工具类演示

    public class TextFileDemo {
        public static void main(){
            String fileName = "/tmp/dirTest/aaa.txt";
            String content = TextFile.read(fileName);
            System.out.print(content);
            
            System.out.println("[ Read End ]");
            
            String content2 = "aaaaaaaa";
            TextFile.write(fileName, content2);
        }
    }

    参考资料

    Page 672, File reading & writing utilities, Thinking in Java 4th.

  • 相关阅读:
    为什么LIKELY和UNLIKELY要用两个叹号
    vuex-persist数据持久化存储插件
    【ejabberd】安装XMPP服务器ejabberd(Ubuntu 12.04)
    Dynamics CRM2013 picklist下拉项行数控制
    jdk1.8新日期时间类(DateTime、LocalDateTime)demo代码
    webpack插件解析:HtmlWebpackPlugin是干什么的以及如何使用它
    marked实现
    Vue组件使用、父子组件传值
    VUE启动报错
    nodejs创建vue项目
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5544673.html
Copyright © 2011-2022 走看看