java 写一个"HelloJavaWorld你好世界"输出到操作系统文件Hello.txt文件中

package com.beiwo.homework;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo5 {
    /**
     * 在程序中写一个"HelloJavaWorld你好世界"输出到操作系统文件Hello.txt文件中
     *
     * 程序分析:文件写入,要用到输出流FileOutputStream
     * 步骤:
     *     1.找到目标文件
     *     2.建立通道
     *     3.写入数据
     *     4.关闭资源
     * */
    public static void main(String[] args) {
        // 向文件C:/Hello.txt,写入内容
        File file = new File("C:\\Users\\cdlx2016\\Desktop\\Hello.txt");
        FileOutputStream fos = null;
        try {
            // 创建输出流
            fos = new FileOutputStream(file);
            // 把String类型的字符串转化为byte数组的数据保存在输出流中
            fos.write("HelloJavaWorld你好世界".getBytes());
        } catch (Exception e) {
            System.out.println("写入异常");
            throw new RuntimeException(e);
        } finally {
            try {
                // 关闭输出流
                fos.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                System.out.println("关闭失败");
                throw new RuntimeException(e);
            }
        }
    }
}

 

posted @ 2016-12-06 10:15  随行-LV  阅读(3979)  评论(0编辑  收藏  举报