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

WriteFile.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 the 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

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment