인터넷의 이미지를 자바 URL 클래스를 활용하여 얻어와 파일로 저장하기

안녕하세요

이번 시간에는 네이버나 구글, 기타 웹 페이지의 이미지를

URL 클래스를 이용해 담아와

파일로 저장하는 예제를 올려봅니다.


제가 불러들일 이미지는


박근혜 대통령이 이번에 최순실 사태로 국민들에게 고개 숙여 사죄하는 이미지입니다.

여담이지만 대한민국.. 제발 정신좀 차렸으면 좋겠습니다.

정말 안썩은 곳 찾기 힘들 정도로 우리나라 너무 부패합니다.

자 어쨋든 소스코드는 아래와 같습니다.

==========================================================


public class test {
public static void main(String[] args) throws IOException {

String str = "http://imgnews.naver.net/image/020/2016/10/26/81004225.1_99_20161026030722.jpg?type=w540";
URL url=new URL(str);
URLConnection ucon=url.openConnection();
ucon.connect(); // 연결

int fsize=ucon.getContentLength();
System.out.println("파일의 크기 : "+fsize);
String contentType=ucon.getContentType();
System.out.println("파일의 컨텐트 타입 : "+contentType);

InputStream is=ucon.getInputStream(); // 입력스트림을 얻자
//인터넷 상의 이미지 파일을 로컬 컴퓨터로 카피하세요
//에러코드 - 2바이트 스트림(InputStreamReader)을 쓰면 안됨
//InputStreamReader ir = new InputStreamReader(is);
//copy3.jpg

//조금 비효율적
/* File file1 = new File("copy3.jpg");
FileOutputStream fos = new FileOutputStream(file1);*/

//효율적
BufferedInputStream bis=new BufferedInputStream(is);
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("copy3.jpg"));

//count 변수는 파일 크기를 알아보기 위해서임
int input=0, count=0;

byte[] data=new byte[1024];

while((input=bis.read())!=-1){
bos.write(data, 0, input);
bos.flush();
count+=input;
}

bos.close();
bis.close();
is.close();
System.out.println(count+"바이트 카피 완료!");

}
}

==========================================================

실행 결과


콘솔창에는 위와 같이 파일의 크기, 컨텐트 타입 등의 정보가 출력되고

패키지 익스플로러를 새로 고침하면

copy3.jpg 라는 파일이 생성됩니다.



네..

이상으로 포스팅 마치겠습니다~!

댓글 없음:

댓글 쓰기