Java Program Write to File

« Previous Program Next Program »

Write to File

To write some content in a file in Java programming, first you have to ask to the user to enter the file name with extension to open it and then write some content inside the file. After writing the contents to the file, you must have to close the file.

Java Programming Code to Write to File

Following Java Program ask to the user to enter the file name to open (if file present inside the directory) or create (if file not present inside the directory), then ask to the user to enter how many sentence/line he/she want to write and then user have to enter that number of lines/sentences to store these lines/sentences inside the files for further use :

/* Java Program Example - Write to File */
import java.util.Scanner;

public class JavaProgram
    public static void main(String[] input)
        String fname;
        Scanner scan = new Scanner(;
        // enter the name of file to create a file and write some content inside
        System.out.print("Enter File Name with Extension (like demo.txt) : ");
        fname = scan.nextLine();
            // assume the default encoding
            FileWriter fileWriter = new FileWriter(fname);
            // always wrap FileWriter in BufferedWriter
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            // Note that write() method does not automatically
            // append a newline character
            int len;
            System.out.print("How many Sentence/Line you Want to Enter ? ");
            len = scan.nextInt();
            int i;
            String sentence;
            System.out.print("Enter " +len+ " Lines of Sentences followed by Enter : ");
            for(i=0; i<len+1; i++)
                sentence = scan.nextLine();
            // always close the file
        catch(IOException ex)
            System.out.println("Error writing to file named '" +fname+ "' ..!!");

When the above Java Program is compile and executed, it will produce the following output:

Java Program write to file

Let User entered the following 3 number of lines/sentences, i.e., :

  1. Hello, Java!
  2. I am a File
  3. My name is demo.txt

After writing the above three lines, you can check in the file named 'demo.txt' in the current directory. That file contain these three lines.

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Java Online Test

« Previous Program Next Program »

© Copyright 2021. All Rights Reserved.