Copying a file to an output stream - Java File Path IO

Java examples for File Path IO:File Stream

Description

Copying a file to an output stream

Demo Code

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) {
    Path sourceFile = FileSystems.getDefault().getPath(
        "C:/home/docs/users.txt");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
      Files.copy(sourceFile, outputStream);
      byte arr[] = outputStream.toByteArray();
      System.out.println("The contents of " + sourceFile.getFileName());
      for (byte data : arr) {
        System.out.print((char) data);
      }/*from w w  w .j av a  2  s .  c o m*/
      System.out.println();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

  }
}

Related Tutorials