Friday, 24 May 2019

Java: Create and write text content to a file


Approach 1: Using PrintWriter class
Example
PrintWriter writer = new PrintWriter(filePath, "UTF-8");
writer.println(content);

App.java
package com.sample.app;

import java.io.PrintWriter;

import javax.script.ScriptException;

public class App {

 public static boolean writeContent(String filePath, String content) {
  try (PrintWriter writer = new PrintWriter(filePath, "UTF-8");) {
   writer.println(content);
  } catch (Exception e) {
   return false;
  }

  return true;
 }

 public static void main(String args[]) throws ScriptException {
  writeContent("/Users/krishna/Documents/welcome.txt", "Welcome to Java Programming");
 }
}

Run App.java and open welcome.txt, you can see below content.
Welcome to Java Programming

Approach 2: Using Files.write method
Example
Files.write(file, lines, Charset.forName("UTF-8"));


App.java
package com.sample.app;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import javax.script.ScriptException;

public class App {

 public static boolean writeContent(String filePath, String content) {
  if (filePath == null || content == null) {
   throw new IllegalArgumentException("filePath and content must not be null");
  }
  List<String> lines = Arrays.asList(content);
  Path file = Paths.get(filePath);
  try {
   Files.write(file, lines, Charset.forName("UTF-8"));
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
  return true;
 }

 public static void main(String args[]) throws ScriptException {
  writeContent("/Users/krishna/Documents/welcome.txt", "Welcome to Java Programming");
 }
}

Approach 3: Using BufferedWriter
Example
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "utf-8"));
writer.write(content);


App.java
package com.sample.app;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.script.ScriptException;

public class App {

 public static boolean writeContent(String filePath, String content) {
  if (filePath == null || content == null) {
   throw new IllegalArgumentException("filePath and content must not be null");
  }

  try (Writer writer = new BufferedWriter(
    new OutputStreamWriter(new FileOutputStream(filePath), "utf-8"))) {
   writer.write(content);
  }catch(Exception e) {
   return false;
  }
  
  return true;
 }

 public static void main(String args[]) throws ScriptException {
  writeContent("/Users/krishna/Documents/welcome.txt", "Welcome to Java Programming");
 }
}


You may like



1 comment: