iT邦幫忙

0

Java OutputStream, PrintWriter 如何寫檔與輸出字串 範例教學與用法

Aiden 2019-08-08 17:41:1912733 瀏覽

相信各位都有遇過要寫檔, 或輸出字串的情境

OutputStream 與 PrintWriter 可說是最常見的兩種方式, 那這兩種有何差異呢?

來看兩個簡單的範例:

首先在C槽底下手動建立一個資料夾 example

public static void main(String[] args) {
    String str = "HelloWorld!!";
    File file = new File("C:/example/hello.txt);
    PrintWriter printWriter = new PrintWriter(file);
    printWriter.write(str);
    printWriter.close();
}

我們可以看到, 在example資料夾底下出現了hello.txt
如果你只是要輸出簡單的字串, 用PrintWriter是一個很好的選項。

public static void main(String[] args) {
    String str = "HelloWorld!!";
    File file = new File("C:/example/hello.txt);
    FileOutputStream fos = new FileOutputStream(file);
    byte[] strToByte = v.getBytes();
    fos.write(strToByte);
    fos.close();
}

聰明的同學可以發現, 第二段程式碼跟第一段有些許相似, 只是輸出方式不同
OutputStream 把要輸出的內容, 轉成byte再輸出, 在某些情況下非常好用。

出現以下錯誤, 代表你的C槽底下沒有這個資料夾, 故無法建立檔案
手動建立一個example資料夾即可。

java.io.FileNotFoundException: C:\example\hello.txt (系統找不到指定的路徑。)

那有沒有辦法用程式自動建立資料夾呢, 當然可以!!
將第二個範例加上簡單的幾行程式

public static void main(String[] args) {
    String str = "HelloWorld!!";
    File folder = new File("C:/example");
    if(!folder.exists()){
        folder.mkdir();  //建立資料夾
    }
    File file = new File("C:/example/hello.txt");
    FileOutputStream fos = new FileOutputStream(file);
    byte[] strToByte = v.getBytes();
    fos.write(strToByte);
    fos.close();
}

這裡的exists(), 可以判斷資料夾是否存在, 存在傳回true, 不存在傳回false
搭配mkdir(), 就可以建立資料夾了。

如果需要建立大量檔案或資料夾, 可以跟for迴圈搭配使用, 有興趣的朋友們可以練習看看!!
PS.注意檔名不要重複了喔


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言