Programming in Java
Object Oriented in Java
Advanced topics in Java
Modal Box
Tutorials
File Handling
The classes for file read and write are also present in java.io package .
Even java has many ways to read data from a given file, one of which we are using as following :
This program will display all the contents of a given file on the console .
import java.io.*;
public class ReadFileExample
{
public static void main(String args[])
{
try{
File file = new File("C:\\Users\\sharp\\Desktop\\test.txt");
FileReader fr=new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s=null;
while ((s = br.readLine()) != null)
System.out.println(s);
}
catch(Exception ex)
{
System.out.println(“Exception=”+ex);
}
}
}
Java program to write the contents into a file :
import java.io.*;
class FileWriterDemo
{
public static void main(String[] args) throws IOException
{
try{
File file = new File("C:\\Users\\sharp\\Desktop\\out.txt"); //file being created if it does not exist.
FileWriter fw=new FileWriter(file);
fw.write("Content to be written");
fw.close();
System.out.println("File written");
}
catch(Exception ex)
{
System.out.println("Exception is"+ex);
}
}
}
Video/ C Introduction
Watch video in full size