Java - File Input Output PrintStream

Introduction

PrintStream can print any data type values, primitive or object, in a suitable format.

Its methods do not throw an IOException.

In case of IOException, it sets an internal flag, rather than throwing the exception to the caller.

The flag can be checked using its checkError() method, which returns true if an IOException occurs during the method execution.

PrintStream has an auto-flush capability.

You can turn on the auto-flush using its constructor.

boolean autoFlush = true;
PrintStream ps = new PrintStream(new FileOutputStream(destFile), autoFlush);

Auto-flush will flush its contents when a byte array is written.

println() method writes data and appends a newline character.

Some of the important methods in PrintStream class are as follows:

print(Xxx arg)
println(Xxx arg)
printf()

The following code shows how to use the PrintStream Class to Write to a File.

Demo

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;

public class Main {
  public static void main(String[] args) {
    String destFile = "luci3.txt";

    try (PrintStream ps = new PrintStream(destFile)) {
      // Write data to the file. println() appends a new line
      // and print() does not apend a new line
      ps.println("line 1");
      ps.println("line 2");
      ps.println("line 3");
      ps.print(" from book2s.com");

      // flush the print stream
      ps.flush();/*from w  w  w  .jav  a 2s. c o m*/

      System.out.println("Text has been written to "
          + (new File(destFile).getAbsolutePath()));
    } catch (FileNotFoundException e1) {
      FileUtil.printFileNotFoundMsg(destFile);
    }
  }
}

class FileUtil {
  // Prints the location details of a file
  public static void printFileNotFoundMsg(String fileName) {
    String workingDir = System.getProperty("user.dir");
    System.out.println("Could not find the file '" + fileName + "' in '"
        + workingDir + "' directory ");
  }

  // Closes a Closeable resource such as an input/output stream
  public static void close(Closeable resource) {
    if (resource != null) {
      try {
        resource.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Result