Sunday, 15 July 2018

Java write to a file using FileWriter

Below statements write data to a file.



Find the below working application.

Test.java

package com.sample.app;

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

public class Test {

 public static void write(final File file, final String data) {
  if (data == null || data.isEmpty()) {
   System.out.println("data is null (or) empty");
   return;
  }

  if (file == null) {
   System.out.println("file is null");
   return;
  }

  try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
   writer.write(data);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String args[]) {
  File file = new File("app.log");
  write(file, "Hello World");
 }
}

You may like


No comments:

Post a Comment