Let’s see how the FileWriter and FileReader works for create a file and write content of it and retrieve the content.
- First you need to crate a new file using FIle in java.
File file = new File("give a name.txt");
2. Then use that file for create a new FileWriter object. Then you can write the content for the text file that you created using BufferedWriter.
File file = new File("E:\\E-Learning(otherS)\\wordpress-blog\\sumi.txt"); FileWriter fw=new FileWriter(file); fw.write("My name is sumith");//this is for flush the content if not write properly. fw.write("I'm 23 years old");//close FileWriter fw.flush(); fw.close();
3. Then using FileReader you can get the content of the file and print it.
FileReader fr = new FileReader(file); char array[] = new char[50]; fr.read(array); for(char c : array){ System.out.println(c); }
- This is the full code in java.
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileWriterClass { public static void main(String args[]) throws IOException{ File file = new File("E:\\E-Learning(otherS)\\wordpress-blog\\sumi.txt"); FileWriter fw=new FileWriter(file); fw.write("My name is sumith"); fw.write("I'm 23 years old"); fw.flush(); fw.close(); FileReader fr = new FileReader(file); char array[] = new char[50]; fr.read(array); for(char c : array){ System.out.println(c); } } }