Reading and writing to a file in java

In this blog we will know how to read and write to a file in java.

 

/*File reading by using FileInputStream/FileReader*/

import  java.io.*;

import java.util.*;

public class readFile

{

public static void main(String arg[])throws Exception

{

System.out.print("Provide name of file to read ");

Scanner sc=new Scanner(System.in);

String s=sc.next();

//FileInputStream fis=new  FileInputStream(s);

FileReader fis=new  FileReader(s);

int x;

while((x=fis.read())!=-1)

System.out.print((char)x);

}

}

 

compile

javac readFile.java

java readFile

 

/*File writing by using FileOutputStream/FileWriter*/

import  java.io.*;

import java.util.*;

public class writeFile

{

public static void main(String arg[])throws Exception

{

Scanner sc=new Scanner(System.in);

System.out.print("Provide file name:");

String fname=sc.next();

System.out.print("Provide data to be written:");

String data=sc.next();

//To use FileWriter

 FileWriter fw=new FileWriter(fname,true);

 fw.write(data);

 fw.close();

}

}

 

compile

javac writeFile.java

java writeFile

  

Ebook Download
View all
Learn
View all