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);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM