Java - Using try resource statement

Description

Using try resource statement

Demo

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
  public static void copy(String records1, String records2) {
    try (InputStream is = new FileInputStream(records1); OutputStream os = new FileOutputStream(records2)) {
      byte[] buffer = new byte[1024];
      int bytesRead = 0;
      while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);/*from w w  w  .ja v a 2s.  c o  m*/
        System.out.println("Read and written bytes " + bytesRead);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    copy("c:\\temp\\test1.txt", "c:\\temp\\test2.txt");
  }
}

Related Topic