[Java] Datei downloaden?

lutoma

lutoma

Möchtegern-Informatiker
Huhu, ich bastel mir grad ein kleines Programm, das die Daten in nem Ordner mit denen von ner liste ausm internet vergleicht und fehlende items runterlädt... funktioniert auch soweit recht gut, nur das downloaden will nicht so recht... die meisten sachen die ich in google gefunden hab sind entweder java-downloadlinks oder funktionieren nicht ;) hat einer von euch ne funktion o.ä. für sowas?
 
PHP:
package downloader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class Downloader {
		public static void downloadFile(String url_str, OutputStream os)
			throws IllegalStateException, MalformedURLException,
			ProtocolException, IOException {

		URL url = new URL(url_str.replace(" ", "%20"));

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setRequestMethod("GET");

		conn.connect();

		int responseCode = conn.getResponseCode();

		if (responseCode == HttpURLConnection.HTTP_OK) {

			byte tmp_buffer[] = new byte[4096];

			InputStream is = conn.getInputStream();

			int n;

			while ((n = is.read(tmp_buffer)) > 0) {
				os.write(tmp_buffer, 0, n);
				os.flush();
			}

		} else {
			throw new IllegalStateException("HTTP response: " + responseCode);
		}
	}

	public static void main(String[] args) {
		try {
			final String url = "http://www.unixboard.de/vb3/images/element/misc/logo_blue.gif";

			FileOutputStream fos = new FileOutputStream(System
					.getProperty("user.home")
					+ File.separator + "logo.gif");

			downloadFile(url, fos);

			fos.close();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}
}
 
Hey, Danke. Das war genau das was ich gesucht hatte, funktioniert perfekt :)
 
Zurück
Oben