Java - File Input Output Byte Write

Introduction

The following code shows the steps to save to a file.

If the file does not exist, the program will create it.

If it exists, it will be overwritten.

Demo

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

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

    // Get the line separator for the current platform
    String lineSeparator = System.getProperty("line.separator");

    String line1 = "test";
    String line2 = "line 2";

    String line3 = "this is a test,";
    String line4 = ".";

    try (FileOutputStream fos = new FileOutputStream(destFile)) {
      // Write all four lines to the output stream as bytes
      fos.write(line1.getBytes());/*w w  w .ja v  a 2 s . c o  m*/
      fos.write(lineSeparator.getBytes());

      fos.write(line2.getBytes());
      fos.write(lineSeparator.getBytes());

      fos.write(line3.getBytes());
      fos.write(lineSeparator.getBytes());

      fos.write(line4.getBytes());

      // Flush the written bytes to the file
      fos.flush();

      // Display the output file path
      System.out.println("Text has been written to "
          + (new File(destFile)).getAbsolutePath());
    } catch (FileNotFoundException e1) {
      FileUtil.printFileNotFoundMsg(destFile);
    } catch (IOException e2) {
      e2.printStackTrace();
    }
  }
}

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