Archive for October, 2010

Writing something into a text file with Java

Wednesday, October 27th, 2010

In relation to a previous post about the code for reading a text file with Java, I will attach another (trivial) code for writing something into a text file. This post is also just for future reference. I have confirmed that it works with Java 1.6.0_18.

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

class SomeClass {
    public static void writeFile(String filename) {
        BufferedWriter fout = null;

        try {
            fout = new BufferedWriter(new FileWriter(filename));

            while (/* Some condition */) {
                // Write something.
                StringBuffer lineBuffer = new StringBuffer();
                lineBuffer.append("abc");
                lineBuffer.append("def");

                fout.write(lineBuffer.toString());
                fout.newLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fout != null) fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        writeFile("sample.txt");
    }
}