Programing

URL 개체에서 파일 개체를 만드는 방법

lottogame 2020. 10. 12. 07:05
반응형

URL 개체에서 파일 개체를 만드는 방법


URL 개체에서 File 개체를 만들어야합니다. 내 요구 사항은 웹 이미지의 파일 개체를 만들어야한다는 것입니다 (예 : Googles 로고).

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = create image from url object

ImageIOURL에서 이미지를로드 한 다음 파일에 쓰기 위해를 사용할 수 있습니다 . 이 같은:

URL url = new URL("http://google.com/pathtoaimage.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

또한 필요한 경우 이미지를 다른 형식으로 변환 할 수 있습니다.


Apache Common IOFileUtils 사용 :

import org.apache.commons.io.FileUtils

FileUtils.copyURLToFile(url, f);

이 메서드는의 콘텐츠를 다운로드 url하고에 저장합니다 f.


Java 7 이후

File file = Paths.get(url.toURI()).toFile();

HTTP URL에서 파일을 생성하려면 해당 URL에서 콘텐츠를 다운로드해야합니다.

URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();

다운로드 한 파일은 프로젝트의 루트에서 찾을 수 있습니다 : {project} /downloaded.jpg


URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

import java.net.*; 
import java.io.*; 
class getsize { 
    public static void main(String args[]) throws Exception {
        URL url=new URL("http://www.supportyourpm.in/jatin.txt"); //Reading
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();

        //Getting size
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD");
        conn.getInputStream();
        System.out.println("Length : "+conn.getContentLength());
    } 
}

참고URL : https://stackoverflow.com/questions/8324862/how-to-create-file-object-from-url-object

반응형