Friday 24 May 2019

Java: Create and write byte array to a file


Approach 1: Using FileOutputStream
FileOutputStream out = new FileOutputStream(filePath);
out.write(content);

App.java
package com.sample.app;

import java.io.FileOutputStream;

import javax.script.ScriptException;

public class App {

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

  try (FileOutputStream out = new FileOutputStream(filePath);) {
   out.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".getBytes());
 }
}

Approach 2: Using Files.write
Path file = Paths.get(filePath);
Files.write(file, content);


App.java
package com.sample.app;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.script.ScriptException;

public class App {

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

  Path file = Paths.get(filePath);
  try {
   Files.write(file, content);
  } catch (IOException e) {
   return false;
  }
  
  return true;

 }

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


You may like


No comments:

Post a Comment