Java Tutorial – How to read write text file using Java

java logo

I have built in a sample code to read and write a text file using JAVA.

Create a file name “helloworld.txt”. This code uses BufferedReader and Bufferedwriter in Java.

Sample working code :

How to read File in Java:

String fileName = filePath + “helloworld.txt”;
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
String str = “”, s = “”;
while ((str = in.readLine()) != null) {
//Execute Your code Here;
}
in.close();
}catch (Exception e) {
System.out.println(“Exception caught during reading text”);
e.printStackTrace();
}
Available on DglobalTech!

 

 

How to write File in Java:

try {
BufferedWriter writer = null;
String fileName = filePath + “helloworld.txt”;
Read, Write and Update file:
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
BufferedWriter writer = null;
String outfileName = filePath + “helloworld_out.rtf”;

try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfileName), “UTF-8″));
} catch (Exception e) {
System.err.println(“Unable to create output file: ” + outfileName);
e.printStackTrace();
}
String str = “”;
while ((str = in.readLine()) != null) {

writer.write(str);
}
in.close();
writer.close();
}catch (Exception e) {
System.out.println(“Exception caught during reading text”);
e.printStackTrace();
}

 

 

Comments are closed.