Write To a File

Introduction

We had a few methods of writing text to a file. The method shown below is the most popular. It  uses a method for writing which uses the java.io.FileWriter class. Note that this class has a constructor which can take two arguments. The filename and a Boolean. When you specify this as true, the FileWriter will append the ouput to the end of the file (if it exists already). You should give the full path to the file. On Windows you should escape the backslash (\), since it is the Java escape character. A file in Windows should therefore look like C:\\path\\to\\my\\file.txt. UNIX and Linux don’t need this. On Windows you can also use UNIX notation; e.g; C:/path/to/my/file.txt.

OutputStreams must always be closed.

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
    out.write("the String to write");
    out.close();
} catch (IOException e) {
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.