Program to Reading and Writing a File in Java

1 year ago
OOP Java

Reading a File

import java io.*;

public class Read {

public static void main(String[] args) {

try {

FileReader reader=new FileReader("C:\\Users\\Raazu\\Desktop\\myfile.txt");

BufferedReader buffer=new BufferedReader(reader); String line=buffer.readLine();

if(line!=null) {

System.out.println(line);

}else {

System.out.println("No Contents to Display");

}

reader.close();

buffer.close();

}catch(Exception e) { System.out.println(e);

}

}

}

 

Writing to a File

 

import java io.*;

public class Write {

public static void main(String[] args) {

try {

FileWriter writer=new FileWriter("C:\\Users\\Raazu\\Desktop\\myfile.txt");

writer.write("This is a content written in file."); writer.write(" This is another content"); System.out.println("Contents written successfully !"); writer.close();

}catch(Exception e) { System.out.println(e);

}

}

}

0
Rusma Khadka
Jan 15, 2023
More related questions

Questions Bank

View all Questions