java字符流

来源:互联网 发布:人工智能语音计算器 编辑:程序博客网 时间:2024/05/01 22:24

java字符流

public class Second {    /**     * 字符流      *   只能读写纯文本     */    public static void main(String[] args) {        String filePath = "d:\\test.txt";        String src = "fjdshkjcjkahsdjfhew";        // 写入字符        writeChar(filePath, src);        // 读取字符        readChar(filePath);    }    private static void writeChar(String filePath, String src) {        char[] charArray = src.toCharArray();        FileWriter fw = null;        try {            fw = new FileWriter(filePath);            fw.write(src);            fw.flush();        } catch (IOException e) {            e.printStackTrace();        } finally {            if(fw!=null){                try {                    fw.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    private static void readChar(String filePath) {        FileReader fr = null;        try {            fr = new FileReader(filePath);            char[] cbuf = new char[4];            int len=0;            StringBuffer sb = new StringBuffer();            while(-1!=(len=fr.read(cbuf))){                String s = new String(cbuf,0,len);                sb.append(s);            }            System.out.println(sb.toString());        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if(fr!=null){                try {                    fr.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}
0 0
原创粉丝点击