10 July 2008

How to Write a Text File in Java

This is a relatively straight forward tutorial on writing text to a file in Java. This question comes up for every coder at some time. Most languages have a quick and easy way to solve this. In Java you can use the bufferedwriter object to do the work for you. You can also determine if the data should be appended to the file or the file should be overwritten. In a nutshell this can be done in a very few lines. import java.io.*; class FileWriteTest { public static void main(String[] args) throws IOException { BufferedWriter bw; bw = new BufferedWriter(new FileWriter("filepath",true)); bw.write("Hello World!"); bw.close(); } } That is it. Notice in the boolean value in FileWriter? Set to true data is appended to your file, set to false, you're starting with clean file. Lets extend this to an activity log, I used this in the Jena Web Service to monitor usage. We can talk about other potentially more preferred log methods in Java later but this can be useful for anyone as a quick maintenance utility. static void activityLog(String logData) { try { BufferedWriter out = new BufferedWriter(new FileWriter(filePath + "jenaWebService.log", true)); // we're appending data out.write(logData + "\n"); out.close(); } catch (Exception e) { System.err.println(e.getMessage()); } }

0 comments: