How to Read and Write a data into a file

File writing and Reading functionality using below code


//Create a Package

package com.selenium.pack;

//Import buffer reader for file

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWrite {

 
    public static void main(String[] args) throws IOException {

        //Create a File

        File f=new File("D:\\Test_Automation\\sample.txt");
        f.createNewFile();

        //Write data into a file

        FileWriter w=new FileWriter("C:\\TestAutomation\\sample.txt");
        BufferedWriter bw=new BufferedWriter(w);
        bw.write("Hi We learn Selenium");
        bw.newLine();
        bw.write("Selenium ");
        bw.flush();

        //Read a File

        FileReader fr=new FileReader("C:\\TestAutomation\\sampletext.txt");
        BufferedReader br=new BufferedReader(fr);
        System.out.println(br.readLine());
        System.out.println(br.readLine());
     

    }

}

No comments:

Post a Comment