java使用BufferedWriter写文件

来源:互联网 发布:手机修改mac地址 编辑:程序博客网 时间:2024/06/09 00:40
import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;/** * * @author outofmemory.cn */public class Main {    /**     * Prints some data to a file using a BufferedWriter     */    public void writeToFile(String filename) {        BufferedWriter bufferedWriter = null;        try {            //Construct the BufferedWriter object            bufferedWriter = new BufferedWriter(new FileWriter(filename));            //Start writing to the output stream            bufferedWriter.write("Writing line one to file");            bufferedWriter.newLine();            bufferedWriter.write("Writing line two to file");        } catch (FileNotFoundException ex) {            ex.printStackTrace();        } catch (IOException ex) {            ex.printStackTrace();        } finally {            //Close the BufferedWriter            try {                if (bufferedWriter != null) {                    bufferedWriter.flush();                    bufferedWriter.close();                }            } catch (IOException ex) {                ex.printStackTrace();            }        }    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().writeToFile("myFile.txt");    }}


package com.yiibai.iofile; import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException; public class WriteToFileExample {public static void main(String[] args) {try { String content = "This is the content to write into file"; File file = new File("/users/mkyong/filename.txt"); // if file doesnt exists, then create itif (!file.exists()) {file.createNewFile();} FileWriter fw = new FileWriter(file.getAbsoluteFile());BufferedWriter bw = new BufferedWriter(fw);bw.write(content);bw.close(); System.out.println("Done"); } catch (IOException e) {e.printStackTrace();}}}


0 0
原创粉丝点击