Visit Software Engineering Space for more articles

How to write contents to file?

Write contents to a text file.

Code Explanation

java.io package provides API to read and write both text and binary data streams. For dealing with binary data there are two top level abstract classes - java.io.InputStream and java.io.OutputStream. On the other hand, to deal with character data top level abstract classes are - java.io.Reader and java.io.Writer. In this case to write content to text file we choose to use java.io.FileWriter, a subclass of java.io.Writer. It's a simple four step process:

  1. Create an instance of java.io.FileWriter with the source file path
  2. Create a java.io.BufferedWriter linking the file writer object
  3. Start writing data to buffer
  4. Flush the buffer

The BufferedWriter is used to minimize actual file access. The BufferedWriter has default size 8 KB. However, it can be changed while creating the BufferedWriter.

In this example we are writing contents to file in append mode. Every time this program is executed data will be appened to the file. If overriding is desired, create the FileWriter object with append flag value as false or ignore the second argument in constructor.

25     /**
26      * Writes content to a file denoted by given path. The data to be written
27      * to file is passed to method as argument.
28      * @param filePath The absolute path of the file.
29      * @param data The data to be written to output file.
30      */
31     public void write(String filePath, String data) {
32         BufferedWriter fileBuffer = null;
33         FileWriter fileWriter = null;
34         File file = new File(filePath);
35         try {
36             /* Create the writer in append mode. In case file overriding
37              * is desired either don't pass the second argument or pass it as false.
38              */
39             fileWriter = new FileWriter(file, true);
40             fileBuffer = new BufferedWriter(fileWriter);
41             // Write current date.
42             fileBuffer.write(Calendar.getInstance().getTime().toString());
43             // Write a new line.
44             fileBuffer.newLine();
45             // Write data
46             fileBuffer.write(data);
47             // Write two new lines.
48             fileBuffer.newLine();
49             fileBuffer.newLine();
50             // Flush the IO streams
51             fileBuffer.flush();
52             fileWriter.flush();
53         } catch (FileNotFoundException ex) {
54             ex.printStackTrace(System.err);
55         } catch (IOException ex) {
56             ex.printStackTrace(System.err);
57         } finally {
58             closeIOStream(fileBuffer);
59             closeIOStream(fileWriter);
60         }
61     }
62 
    

The following method is a helper method to close a given java.io.Writer resource.

67     private void closeIOStream(Writer writer) {
68         if (writer != null) {
69             try {
70                 writer.close();
71             } catch (Exception ex) {
72                 System.err.println("Failed to close output stream.");
73                 ex.printStackTrace(System.err);
74             } finally {
75                 writer = null;
76             }
77         }
78     }
79
    

The main method of program calls write() method to write file content. The target file path and data to be written to file can optionally be passed as command line arguments. If file path and data not passed as input arguments, these are assumed in the program.

80     /**
81      * Main method to write content to file.
82      * @param args Input arguments.
83      */
84     public static void main(String[] args) {
85         String outputFile = "E:/Leisure/poems/fav-x.txt";
86         String data = "My favorite quote - \"Love is balanced. What you give to the world, you get in return\"";
87         if (args.length > 0) {
88             outputFile = args[0];
89         }
90         if (args.length > 1) {
91             data = args[1];
92         }
93         new WriteFile().write(outputFile, data);
94     }
95 }
96 
97 
    

Download

You may download the complete source code from here: