演示如何使用Java BufferedOutputStream類寫文件

jopen 9年前發布 | 1K 次閱讀 Java

下面代碼演示如何使用BufferedOutputStream類寫文件。

使用BufferedOutputStream類寫文件,需要先將字符串轉換為字節數組,然后再寫入。

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*

  • @author outofmemory.cn */ public class Main {

/**

  • Prints some data to a file */ public void writeToFile(String filename) {

BufferedOutputStream bufferedOutput = null;

try {

//Construct the BufferedOutputStream object bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));

//Start writing to the output stream bufferedOutput.write("Line one".getBytes()); bufferedOutput.write("\n".getBytes()); //new line, you might want to use \r\n if you're on Windows bufferedOutput.write("Line two".getBytes()); bufferedOutput.write("\n".getBytes());

//prints the character that has the decimal value of 65 bufferedOutput.write(65);

} catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedOutputStream try { if (bufferedOutput != null) { bufferedOutput.flush(); bufferedOutput.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }

/**

  • @param args the command line arguments */ public static void main(String[] args) { new Main().writeToFile("myFile.txt"); } }</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!