Writing data to a file in Java

By |2015-05-07T01:40:27+05:30May 6th, 2015|java|

The most important question when we attend an interview on ios in Java, how to write data in a file using java. Well here is the example, in which we are going to write the data in a file.

Writing data to a file in Java

package io;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class WriteFile {

    public static void main(String[] args) {
        WriteFile wf = new WriteFile();

    public void write(String file_path) {
        Scanner scanner = null;
        String content_to_write = null;
        BufferedWriter writer = null;
        try {
            System.out.println("Write to File..");
            scanner = new Scanner(System.in);
            content_to_write = scanner.nextLine();
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file_path)));
            if (!content_to_write.equals("done")) {
                writer.write(content_to_write + "\n");
            while (true) {
                content_to_write = scanner.nextLine();
                if (!content_to_write.equals("done")) {
                    writer.write(content_to_write + "\n");
                } else {
        } catch (Exception e) {
        } finally {
            scanner = null;
            content_to_write = null;

To run the above example, you have to create a file on your desktop and give a name as “FileOperations.txt”.  And give the complete path in example at line number 12. While running the example we have to give the inputs(words) to file, the data will be saved in the “FileOperations.txt” file. To terminate the program we have to mention “done” as input.


Write to File..

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment