国产探花免费观看_亚洲丰满少妇自慰呻吟_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();
  }
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 红原县| 琼海市| 江油市| 新宁县| 西畴县| 乌拉特后旗| 三门县| 诸暨市| 绍兴县| 九江市| 荆州市| 内江市| 天台县| 汨罗市| 淮滨县| 通山县| 娄烦县| 合江县| 庆安县| 和田县| 越西县| 鹤岗市| 霸州市| 永安市| 汝南县| 民丰县| 柞水县| SHOW| 廊坊市| 阿克陶县| 当涂县| 左云县| 六盘水市| 成都市| 宁德市| 黔南| 荥经县| 崇礼县| 安福县| 冕宁县| 杂多县|