欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

演示如何使用Java BufferedOutputStream类写文件,,下面代码演示如何使用Bu

来源: javaer 分享于  点击 9910 次 点评:5

演示如何使用Java BufferedOutputStream类写文件,,下面代码演示如何使用Bu


下面代码演示如何使用BufferedOutputStream类写文件。

使用BufferedOutputStream类写文件,需要先将字符串转换为字节数组,然后再写入。

import java.io.BufferedOutputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/**** @author byrx.net*/public class Main {/*** Prints some data to a file*/public void writeToFile(String filename) {BufferedOutputStream bufferedOutput = null;try {//Construct the BufferedOutputStream objectbufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));//Start writing to the output streambufferedOutput.write("Line one".getBytes());bufferedOutput.write("\n".getBytes()); //new line, you might want to use \r\n if you're on WindowsbufferedOutput.write("Line two".getBytes());bufferedOutput.write("\n".getBytes());//prints the character that has the decimal value of 65bufferedOutput.write(65);} catch (FileNotFoundException ex) {ex.printStackTrace();} catch (IOException ex) {ex.printStackTrace();} finally {//Close the BufferedOutputStreamtry {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");}}
相关栏目:

用户点评