zoukankan      html  css  js  c++  java
  • Write to file using a BufferedWriter

    Write to file using a BufferedWriter - A Java Code Example

        Write to file using a BufferedWriter

        When you want to output text to a file it's better to use a Writer class instead of an OutputStream such as the BufferedOutputStream since the purpose of Writer classes are to handle textual content.
        With the BufferedWriter (as opposed to the BufferedOutputStream) you don't have to translate your String parameter to a byte array, and there is also a handy method for writing a new line character.
        In this example we simply write two lines of text, and finally we call flush on the BufferedWriter object before closing it.



        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");
            }
        }

  • 相关阅读:
    laravel 博客
    VSSより、指定したファイルを取得するマクロ(パス入り)
    使用SQLPlus连接Oracle实例
    SSH-Struts第四弹:Struts2学习过程中遇到的问题
    SSH-Struts第三弹:传智播客视频教程第一天上午的笔记
    Prim和Kruskal求最小生成树
    tarjan算法求强连通分量
    shutdown TCP 端口445
    Eclipse导出apk
    [模板]tarjan求强连通分量
  • 原文地址:https://www.cnblogs.com/lexus/p/2391517.html
Copyright © 2011-2022 走看看