Java Program to Write to a File

This article is created to cover a program in Java that writes some content entered by user at run-time of the program, to a file also entered by user.

Write to a File in Java

The question is, write a Java program to write some text to a given file. The program given below is its answer:

import java.util.Scanner;
import java.io.*;

public class CodesCracker
{
   public static void main(String[] args)
   {
      String myfile, content;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the Name of File: ");
      myfile = scan.nextLine();
      
      try
      {
         FileWriter fw = new FileWriter(myfile);
         System.out.print("\nEnter the Content: ");
         content = scan.nextLine();
         fw.write(content);
         fw.close();
         System.out.println("\nContent written to the file successfully.");
      }
      catch(IOException ioe)
      {
         System.out.println("\nException: " +ioe);
      }
   }
}

The snapshot given below shows the sample run of above program with user input codescracker.txt as the name of file, and Hey, I'm the content. as content to write it into the given file:

java program write to file

If the file codescracker.txt is already available in your current directory, the directory where the above source code is saved. Then the content gets overwritten to this file. Otherwise a file with same name gets created and the content gets written. Here is the snapshot of the current directory, along with opened file codescracker.txt in my case, after executing the above program:

write to file in java

Write to File Line by Line in Java

This program is created in a way to allow user to write multiple lines of text to a file. That is, this program is based on the write content to a file line by line.

import java.util.Scanner;
import java.io.*;

public class CodesCracker
{
   public static void main(String[] args)
   {
      String fileName, text;
      int noOfLines, i;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter File's Name: ");
      fileName = scan.nextLine();
      try
      {
         FileWriter fw = new FileWriter(fileName);
         BufferedWriter bw = new BufferedWriter(fw);
         
         System.out.print("How many lines of content to write ? ");
         noOfLines = scan.nextInt();
         System.out.print("Enter " +noOfLines+ " lines of text: ");
         for(i=0; i<noOfLines+1; i++)
         {
            text = scan.nextLine();
            text = text + "\n";
            bw.write(text);
         }
         System.out.println("\nContent written to the file successfully.");
         bw.close();
      }
      catch(IOException ex)
      {
         System.out.println("Error writing to file named '" +fileName+ "' ..!!");
      }
   }
}

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »