ABOUT ME

95.12.1 / 취준생 / Java

Today
Yesterday
Total
  • 11. ex1 - (5) ExceptionDemo5 (URL로 사진 저장, 복사)
    java/코드 리뷰 2020. 4. 23. 19:03
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    package ex1;
     
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
     
    public class ExceptionDemo5 {
     
        public static void main(String[] args) {
            try {
                ExceptionDemo5.saveImage("https://lh3.googleusercontent.com/proxy/m1r7TL7vhUtCOxL1oUvednM4rqZiHJtmJ7gl7O0TsReUlbrmlvfqZeHfrW0Bp0CiZdyz3URuvkDRHf-P-ADHZo_TqFWKdMsbsSAJvNbcZD2G-cldwKINFBVpBNGUJhc1i74f9vOGd_Wdkg");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     
        }
     
        // 예외처리를 saveImage() 메서드를 호출한 측에 위임
        // throws 키워드 사용시 해당 메서드 안에서 발생되는 예외에 대한 처리를 호출한 측에 위임
        private static void saveImage(String path) throws MalformedURLException, IOException {
            URL url = new URL(path);
            InputStream in = url.openStream();
     
            FileOutputStream out = new FileOutputStream("c:/files/iu.jpg");
            byte[] buf = new byte[1024];
            int len = 0;
            while ((in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
            
            ExceptionDemo5.copy(inout);
     
        }
        
        private static void copy(InputStream in, OutputStream outthrows IOException {
            byte[] buf = new byte[1024];
            int len = 0;
            while ((in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
        }
        
    }
     
     
Designed by Tistory.