Java IO examples of character-output stream

Character-output stream a more stringent wording

public class IOTest4 {

    public static void main(String[] args) {

        Writer writer = null;
        //IO流是需要关闭的,如果不这样设计就会不能关闭资源
        try {
            //这里使用相对路径,true代表文件写入方式是在后面追加 可不选
            writer = new FileWriter("test1.txt", true);

            //写数据...
            writer.write("HelloWorld");

            //当大量写入文件数据时要合理的使用flush 清空缓存区,把内容写入到文件中
            //writer.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //判断writer不是空 防止空指针异常
            if(writer != null) {
                try {
                    //在关闭前会做flush的事情 把缓存里的数据冲入文件
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Guess you like

Origin www.cnblogs.com/seviyan/p/11647834.html