国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java文件輸出流寫文件的幾種方法

2019-11-26 15:33:40
字體:
來源:轉載
供稿:網友

java文件輸出流是一種用于處理原始二進制數據的字節流類。為了將數據寫入到文件中,必須將數據轉換為字節,并保存到文件。

復制代碼 代碼如下:

package com.yiibai.io;

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

public class WriteFileExample {
 public static void main(String[] args) {

  FileOutputStream fop = null;
  File file;
  String content = "This is the text content";

  try {

   file = new File("c:/newfile.txt");
   fop = new FileOutputStream(file);

   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   fop.flush();
   fop.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fop != null) {
     fop.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}
//更新的JDK7例如,使用新的“嘗試資源關閉”的方法來輕松處理文件。
package com.yiibai.io;

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

public class WriteFileExample {
 public static void main(String[] args) {

  File file = new File("c:/newfile.txt");
  String content = "This is the text content";

  try (FileOutputStream fop = new FileOutputStream(file)) {

   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   fop.flush();
   fop.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石泉县| 湟源县| 周至县| 浪卡子县| 新密市| 千阳县| 南宫市| 鄂尔多斯市| 财经| 若尔盖县| 亚东县| 福清市| 兴宁市| 遵义县| 麻阳| 灌云县| 凌源市| 赤城县| 维西| 合作市| 宜良县| 栖霞市| 济南市| 永嘉县| 贺兰县| 岐山县| 胶州市| 左贡县| 江永县| 西乌珠穆沁旗| 台州市| 阳春市| 满城县| 蓝田县| 宝兴县| 大城县| 禹城市| 泰兴市| 庄河市| 沽源县| 武川县|