Java Examples - Write to a file


Advertisements


Problem Description

How to write into a file ?

Solution

This example shows how to write to a file using write method of BufferedWriter.

import java.io.*;

public class Main {
   public static void main(String[] args) {
      try {
         BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
         out.write("aString");
         out.close();
         System.out.println("File created successfully");
      }
      catch (IOException e) {
      }
   }
}

Result

The above code sample will produce the following result.

File created successfully.

The following is the another example of write into a file in java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileExample {
   public static void main(String[] args) {
      try {
         String content = "TutorialsPoint is one the best site in the world";
         File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         if (!file.exists()) {
            file.createNewFile();
         } 
         FileWriter fw = new FileWriter(file.getAbsoluteFile());
         BufferedWriter bw = new BufferedWriter(fw);
         bw.write(content);
         bw.close();
         
         System.out.println("Done");
      } catch (IOException e) {
         e.printStackTrace();
      } 
   } 
}

The above code sample will produce the following result.

Done

java_files.htm

Advertisements