이전 2016 >/JAVA

1. URL 경로 파일 다운로드해서 TXT형 저장하기

망이방 2014. 7. 23. 15:36

/* URL로 M3U8파일 파싱해서 재생시간을 구하는 것이 필요했음. */



import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

 

public class HttpDownloader {

    public static void main(String[]arg) {

        FileOutputStream fos = null;

        InputStream is = null;

        try {


// 다운로드할 URL 주소

String sourceUrl = "http://파일주소";  

// 생성될 TEXT 파일 경로,파일명

String targetFilename = "c:/1/1.txt";


            fos = new FileOutputStream(""+ targetFilename);

            URL url = new URL(sourceUrl);

            URLConnection urlConnection = url.openConnection();

            is = urlConnection.getInputStream();

            byte[] buffer = new byte[1024];

            int readBytes;

            while ((readBytes = is.read(buffer)) != -1) {

                fos.write(buffer, 0, readBytes);

            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (fos != null) {

                    fos.close();

                }

                if (is != null) {

                    is.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}