浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Write to file using a BufferedWriter - A Java Code Example

    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;

    /**
     *
     * @author javadb.com
     */
    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");
        }
    }

        



    The output to the file will look like this when you run the code:

    Writing line one to file
    Writing line two to file

posted on 2012-03-12 10:29  lexus  阅读(425)  评论(0编辑  收藏  举报