Java Programming | Writing the File

Introduction.

This is a tutorial for writing the file in java. The program takes a string from the user and saves it in a txt file. The program is extendable. Go enjoy the program. Lets Begin…

Program for writing the file in java.

//import these as we require them.
import java.io.DataOutputStream;
import java.util.Scanner;
import java.io.FileOutputStream;
import java.io.IOException;
 
// the name of our class its public
public class WriteFile {
    //void main
    public static void main(String args[])throws IOException{
 
        //declare the DataOutputStream obj
          DataOutputStream out = new DataOutputStream(new FileOutputStream("file.txt"));
          //String
          String a;
          //print a message
          System.out.println("Enter you string:");
          //get the input
          Scanner input = new Scanner(System.in);
             a = input.next();
          //Write in the file
          out.writeBytes(a);
          //close the file
          out.close();
          //print the message.
          System.out.println("Your String is Saved in file.txt");
       }
}

Output

Enter you string: hello
Your String is Saved in file.txt

How does it work

  1. You enter the string.
  2. The string is written in file and saved.
  3. The Message that the string is saved is printed.

Extending it

The program can be extended. This is a basic concept of java programming and has lots of applications.

Explanation.

  1. Import those 4 things.
  2. Declare the class as public
  3. Add the void main function
  4. Declare out object.
  5. Add system.out.println() function to print the message to enter string.
  6. Declare the Scanner input object.
  7. Get the Input.
  8. Write the string.
  9. Close the file.
  10. Print the message that string is saved in file.

At the end.

You learnt creating the Java program for Writing the file. So now enjoy the program.

Please comment on the post and share it.

Sharing options: