Java通过阅读器书写器实现按编码读写字符

1. 简介

通过按字节的方式读写文件,实际上是比较底层的,并不算方便。实际程序员可能更喜欢指定编码(如UTF-8),并按字符读写。

Java提供了封装好的阅读器、书写器替我们完成了流-字符转换,我们直接可以操作读写字符的函数即可。

2. 示例

工具类

//工具类
package com.maoge.stream;
import java.io.File;
public class StreamUtils {
    //用于定义每次读取的长度
    public static final int BUFFER_LENGTH=512;
    //文件对象
    public static File FILE_FOR_READ;
    public static File FILE_FOR_WRITE;
    static{
        FILE_FOR_READ=new File("C:\\test.txt"); 
        FILE_FOR_WRITE=new File("C:\\result.txt"); 
    }
}

阅读器、书写器

package com.maoge.stream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
//阅读器、书写器示例
public class ReaderWriterDemo {
    //测试入口
    public static void main(String[] args){
        //书写器OutputStreamWriter示例
        writeText("哈利路亚");
        //阅读器InputStreamReader示例
        readText();
        //可以在InputStreamReader上再串联一个BufferedReader,实现按行读取,这个就非常方便了。
        System.out.println("开始按行读取"); 
        readLine();
    }
    public static void writeText(String text){
        OutputStreamWriter out=null;
        try {
            //OutputStreamWriter是按字符(非字节了)方式写入,同时可以指定编码
            out=new OutputStreamWriter(new FileOutputStream(StreamUtils.FILE_FOR_WRITE),"UTF-8");
            out.write(text);
            out.flush();
        } catch (Exception e) {
            System.out.println(e.toString());
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }
    }
    public static void readText(){
        InputStreamReader in=null;
        try{
            //注意阅读器一次读取一个字符
            in=new InputStreamReader(new FileInputStream(StreamUtils.FILE_FOR_READ),"UTF-8");
            StringBuilder sb=new StringBuilder();
            int readInt;
            while((readInt=in.read())!=-1)
                sb.append((char)readInt);
            System.out.println(sb.toString());
        }catch(Exception e){
            System.out.println(e.toString());
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }
    }
    public static void readLine(){
        BufferedReader br=null;
        try{
            br=new BufferedReader(new InputStreamReader(new FileInputStream(StreamUtils.FILE_FOR_READ),"UTF-8"));
            String line = null;
            while((line = br.readLine())!=null)
            {
                System.out.println(line); 
            }
        }catch(Exception e){
            System.out.println(e.toString());
        }finally{
            try {
                br.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }
    }
}

上一篇:Nginx 内置变量,细化规则,真实IP获取及限制连接请求


下一篇:Android性能优化(一)之启动加速35%