Posted in Java

[Java Core] How to read/write file in Java ?

java_logo_100

In Java, we often face the requirement to read content from a file or write content to file. In Java, we have many ways to do that :).

A) How to READ file?

  • Using BufferedReader is the simplest and most common-used method. It helps us read file line by line:

public class ReadWriteFileHandler {

public void readFileByBufferedReader(String fileName) {
 BufferedReader br = null;
 FileReader fr = null;
 try {
   fr = new FileReader(fileName);
   br = new BufferedReader(fr);
   String currentLine = "";
   while ((currentLine = br.readLine()) != null) {
// Read line by line
      System.out.println(currentLine);
   }
 } catch (IOException e) {
   e.printStackTrace();
 } finally {
   try {
     if (br != null)
        br.close();
     if (fr != null)
        fr.close();
    } catch (IOException ex) {
     ex.printStackTrace();
    }
   }
 }

}

 

 

B) How to WRITE file?

Using BufferedWriter to write content to a file, create the file if doesn’t exist, the existing content will be overridden.

The BufferedWriter is a character stream class to handle the character data. Unlike byte stream (convert data into bytes), you can just write the strings, arrays or character data directly to a file.

Please find an example below:


public void writeFile(String fileName, String content) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("Write Done !");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();

}

}
}

 

Basically, you can refer above code from ReadWriteFileHandler.java

Hope this topic helpful for you :), please share if you like it 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s