How to write file in Java ?

There are different ways to write file in Java. Many times we need to write some data in file using Java. Lets see couple of methods one by one to create/write file in Java.

Say we want to write our file inside D drive named as hello.txt and our data is in String format which has value as "Hello infybuzz".

1) Using FileWriter and Automatic Resource Management

package com.infybuzz.file;

import java.io.FileWriter;

public class FileWriterDemo1 {

 public static void main(String[] args) {
  try ( FileWriter fileWriter = new FileWriter("D:\\hello.txt") ) {
      
   String fileDataStr = "Hello infybuzz";
   
   fileWriter.write(fileDataStr);
   
  } catch(Exception ex) {
   ex.printStackTrace();
  }
 }

}

If you do not have idea about Automatic Resource management then just check out below post.
Automatic Resource Management in Java

2) Using FileWriter & BufferedWriter and Automatic Resource Management

package com.infybuzz.file;

import java.io.BufferedWriter;
import java.io.FileWriter;

public class FileWriterDemo2 {

 public static void main(String[] args) {
  try (  FileWriter fileWriter = new FileWriter("D:\\hello.txt");
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter) ) {
   
   String fileDataStr = "Hello infybuzz";
   
   bufferedWriter.write(fileDataStr);
   
  } catch(Exception ex) {
   ex.printStackTrace();
  }
 }

}

3) Using FileOutputStream and Automatic Resource Management

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.infybuzz.file;

import java.io.FileOutputStream;

public class FileWriterDemo3 {

 public static void main(String[] args) {
  try ( FileOutputStream outputStream = new FileOutputStream("D:\\hello.txt") ) {
      
   String fileDataStr = "Hello infybuzz";
   
   outputStream.write(fileDataStr.getBytes());
   
  } catch(Exception ex) {
   ex.printStackTrace();
  }
 }

}

How to read file in Java using BufferedReader ?


0 Comments