Program to create text file, write some data and read the same using single character method without using string functions

 In this tutorial, you'll learn how to create TEXT file, write some data to file and read the data from text file.

Before going to start you should aware of the following concepts:



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

public class TextFileCreateWriteReadData {
	
  public static void main(String args[]) {
    
    try { 
      
      File f = new File("demo.txt");
      
      // Step 1 - Create a TEXT file
      f.createNewFile();
      System.out.println("TEXT file created successfully !!!\n");
      
      // Step 2 - Write to TEXT file
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter some text to write into file ==>");
      String data = scan.nextLine();
            
      FileWriter fw = new FileWriter("demo.txt");   // Creates a FileWriter object
      fw.write(data);
      fw.flush();
      fw.close();
      
      // Step 3 - Read data from TEXT file
      FileReader fr = new FileReader("demo.txt");   // Creates a FileReader object
      char x[] = new char[30];
      fr.read(x);    // Reads the contents to array
      
      System.out.println("\n\nReading data from TEXT file....");
      for(char c : x) {
        System.out.print(c);  // Print character one by one
      }
      
      fr.close();
    }
    catch(IOException ioe) {
      System.out.println(ioe);
    }
  }
}
OUTPUT

C:\>javac TextFileCreateWriteReadData.java
C:\>java TextFileCreateWriteReadData 
TEXT file created successfully !!!

Enter some text to write into file ==>
Hello I am Rahul


Reading data from TEXT file....
Hello I am Rahul

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative