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

Java examples for File Path IO:File Stream

Description

Copying an input stream to a file

Demo Code

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
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 newFile = FileSystems.getDefault().getPath(
        "C:/home/docs/java7WebSite.html");
    URI url = URI.create("http://jdk7.java.net/");
    try (InputStream inputStream = url.toURL().openStream()) {

      Files.copy(inputStream, newFile);
      System.out.println("Site copied successfully!");
    } catch (MalformedURLException ex) {
      ex.printStackTrace();/*from   w w  w.  j  a va 2  s .co m*/
    } catch (IOException ex) {
      ex.printStackTrace();
    }

  }
}

Related Tutorials