Java Files copy to OutputStream

Description

Java Files copy to OutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
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("Main.java");
      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  ava  2s .  c  o m*/
         System.out.println();
      } catch (MalformedURLException ex) {
         ex.printStackTrace();
      } catch (IOException ex) {
         ex.printStackTrace();
      }

   }

}



PreviousNext

Related