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.

  • 相关阅读:
    logcat 自动清屏
    eclipse debug (调试) 学习心得
    黑马面试题
    如何分析解决Android ANR
    植物大战僵尸(一)
    cocos2d-小游戏
    VIM编辑器的使用
    面试题之排序总结
    面试题链表总结
    微软大楼设计方案(中等)(2017 计蒜之道 初赛 第六场)
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5544673.html
Copyright © 2011-2022 走看看