Thursday, August 9, 2012

Writing in a File using Java

In my previous posts I talked about how to Create and Delete files using Java. Now, once you have created a file the next step is to write some content in those files and that can be achieved by using:
  1. BufferedWriter, or
    FileWriter writer = new FileWriter(fileToWriteIn);
    BufferedWriter bufferedWriter = new BufferedWriter(writer);
    bufferedWriter.write(toWrite);
    bufferedWriter.close();
  2. FileOutputStream.
    FileOutputStream stream = new FileOutputStream(fileToWriteIn);
    stream.write(toWrite.getBytes());
    stream.flush();
    stream.close();
There are classes like FileWriter available to perform write operation on a file but since writer sends its output immediately to the underlying character or byte stream. So that is why until prompt output is required, it is recommended to wrap a BufferedWriter around it.

Here is an example with full code and main method:

package home.flicker.java.io.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class WriteInFile {
    File file = null;
    /**
     * Method to create a file with the given name.
     */
    public boolean createFile(String fileName) {
        boolean result = false;
        file = new File(fileName);
        // creating the new File. The Method createNewFile() returns TRUE if file is successfully created else it returns FALSE.
        try {
            result = file.createNewFile();
        } catch (IOException e) {
            System.err.println("Error while creating file!!! " + e.getMessage());
        }
        return result;
    }
    /**
     * Method to read content from user and write it in given file using BufferedReader.
     */
    public boolean writeInFileWithBufferedWriter(File fileToWriteIn){
        boolean result = false;
        String toWrite = readFromUser("Data to write");
        try {
            FileWriter writer = new FileWriter(fileToWriteIn);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(toWrite);
            bufferedWriter.close();
            result = true;
        } catch (IOException e) {
            System.err.println("Error while writing in file!!! " + e.getMessage());
        }
        return result;
    }

    /**
     * Method to read content from user and write it in given file using FileOutputStream.
     */
    public boolean writeInFileWithFileOutputStream(File fileToWriteIn) {
        boolean result = false;
        String toWrite = readFromUser("Data to write");
        try {
            FileOutputStream stream = new FileOutputStream(fileToWriteIn);
            stream.write(toWrite.getBytes());
            stream.flush();
            stream.close();
            result = true;
        } catch (FileNotFoundException e) {
            System.err.println("Error: File not found!!! How the hell I am supossed to write   :P " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Error while writing in file!!! It's stupid   x( " + e.getMessage());
        }
        return result;
    }

    /**
     * Reads input from user as string and puts the label as question.
     */
    public static String readFromUser(String label) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(label + ": ");
        String input = scanner.next();
        return input;
    }

    /**
     * Main method.
     */
    public static void main(String args[]) throws IOException{
        WriteInFile example = new WriteInFile();
        String fileName = readFromUser("Enter File name");
        example.createFile(fileName);
        example.writeInFileWithBufferedWriter(example.file);  
        example.writeInFileWithFileOutputStream(example.file);
    }
}


The thing with these methods is that they over-write the content which is already in the file. To avoid that you need to append data. Will cover that some other time. 
I hope this post helps you. Share your experience or issues...

No comments:

Follow by Email