Tuesday , January 24 2017
Home / java / Writing data to a file in Java

Writing data to a file in 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();
        wf.write("/home/chandrashekhar/Desktop/FileOperations.txt");
    }

    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");
                    writer.flush();
                } else {
                    break;
                }
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 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.

Output:

Write to File..
sample
data
writing
example
done

About chandrashekhar

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+ ,

Check Also

Type Inference in Java 7 Example

Type Inference in Java 7 is another great addition introduced to ease the developer to type …

Leave a Reply

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