filesize von url

Status
Nicht offen für weitere Antworten.

lumo

Top Contributor
hallo,

habe vor einiger zeit eine klasse geschrieben, die mir daten (binär) von einer url lädt;
heute versuche ich die klasse in mein jetziges projekt einzubinden und siehe da... exception!

ich versuche die dateigröße so auszulesen - habs in ne eigene funktion rausgepackt...
Java:
	public static int getFileSize(String srcUrl) {
		URLConnection conn;
		int size;

		try {
			URL url = new URL(srcUrl);
			conn = url.openConnection();
			size = conn.getContentLength();
			conn.getInputStream().close();
			if (size < 0)
				return -1;
			else
				return size;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

die originale funktion sieht so aus:
Java:
	public static final byte[] getByteFromUrl(String srcUrl) {
		try {
			URL page = new URL(srcUrl);
			URLConnection conn = (HttpURLConnection) page.openConnection();
			InputStream fr = conn.getInputStream();
			int total = conn.getContentLength();
			byte[] buffer = new byte[total];
			fr.read(buffer); // load whole file into buffer
			fr.close();
			return buffer;
		} catch (MalformedURLException mue) {
			System.out.println("Bad URL: " + srcUrl);
		} catch (IOException ioe) {
			ioe.printStackTrace();
			// System.out.println("IO Error: " + ioe.getMessage());
		}
		return null;
	}

könnte mir jemand mitteilen, was ich falsch mache???

PS: meine test-klasse:
Java:
public class Test {
	private static String page = "http://www.java-forum.org";

	public static void main(String[] args) {
		System.out.println(DataCollector.getFileSize(page));
		String data = new String(DataCollector.getByteFromUrl(page));
		System.out.println(data);
	}
}

EDIT:
hab im forum schon gesucht -> kleine info am rande... das laden der url als TEXT funktioniert, allerdings muss ich dort die dateigrösse nicht wissen...
Java:
public static final String getText(String srcUrl) {
		String text = "";
		try {
			URL url = new URL(srcUrl);
			InputStream is = url.openConnection().getInputStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			try {
				String line = null;
				while ((line = reader.readLine()) != null) {
					text += line + "\n\r";
				}
			} finally {
				reader.close();
			}
		} catch (MalformedURLException mue) {
			System.out.println("Bad URL: " + srcUrl);
		} catch (IOException ioe) {
			ioe.printStackTrace();
			// System.out.println("IO Error: " + ioe.getMessage());
		}
		return text;
	}
 
Zuletzt bearbeitet:
Ich fürchte hier stellt sich nicht die Frage, was du falsch machst, sondern eher, was der Sender (Server) falsch macht. "getContentLength()" liest die Dateilänge aus dem Header der Verbindung. Wenn der Server sie dort nicht setzt und das Protokoll ungleich "file" ist, wird -1 zurück gegeben.
 
d.h. ich kann nichts dran ändern...
das ist natürlich unerfreulich, denn so muss ich die ganze datei vorher auf meinen pc laden, bevor ich sie einlesen kann...

EDIT:
dann eben so:
Java:
public static File getBinaryData(String srcUrl) {
		File temp = null;
		try {
			temp = File.createTempFile("java-forum.org", ".download");
			temp.deleteOnExit(); // clean up when VM is gone
		} catch (IOException e) {
			e.printStackTrace();
		}

		int c;
		try {
			URL page = new URL(srcUrl);
			URLConnection conn = (HttpURLConnection) page.openConnection();
			InputStream fr = conn.getInputStream();
			FileOutputStream fw = new FileOutputStream(temp);

			byte[] buff = new byte[1024 * 512]; // 1/2mb slices
			while (((c = fr.read(buff)) != -1)) {
				fw.write(buff, 0, c);
			}
			fr.close();
			fw.close();
		} catch (MalformedURLException mue) {
			System.out.println("Bad URL: " + srcUrl);
		} catch (IOException ioe) {
			System.out.println("IO Error: " + ioe.getMessage());
		}
		return temp;
	}
 
Naja... nicht wirklich. Wenn sichergestellt ist, das der zu erwartende Inhalt nicht endlos ist (i.e. kein Radio-Stream) kannst du ihn in ein ByteArrayOutputStream (besser in ByteBuffer) schreiben und anschliessend in ein byte-Array wandeln.
Java:
        try {
            URL page = new URL(srcUrl);
            URLConnection conn = (HttpURLConnection) page.openConnection();
            InputStream fr = conn.getInputStream();
            OutputStream buf = new ByteArrayOuputStream();
            int i;
            while((i = fr.read()) != -1) { // "-1" -> Signal für End of Stream
              buf.write(i & 0xFF);
            }
            buf.close();
            fr.close();
            return buf.toByteArray();
        } catch (MalformedURLException mue) {
            System.out.println("Bad URL: " + srcUrl);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            // System.out.println("IO Error: " + ioe.getMessage());
        }
        return new byte[0];
@Edit: Fehler sind Flüchtigkeitsfehler...
@TS: Danke fürs verbessern 🙂 \/\/
 
Zuletzt bearbeitet von einem Moderator:
Java:
        try {
            URL page = new URL(srcUrl);
            URLConnection conn = (HttpURLConnection) page.openConnection();
            InputStream fr = conn.getInputStream();
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            int i;
            while((i = fr.read()) != -1) { // "-1" -> Signal für End of Stream
              buf.write(i & 0xFF);
            }
            buf.close();
            fr.close();
            return buf.toByteArray();
        } catch (MalformedURLException mue) {
            System.out.println("Bad URL: " + srcUrl);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            // System.out.println("IO Error: " + ioe.getMessage());
        }
        return new byte[0];

^^ lauffähiger code 🙂

danke, so wirds gemacht
 
Status
Nicht offen für weitere Antworten.

Zurück
Oben