Descarrega.java 2.2 KB
package com.upc.pbe.upcnews;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.util.Log;

//Descarrega un arxiu i el guarda o retorna en String
public class Descarrega extends AsyncTask<Object, Object, Object>
{

	final static String TAG = "Descarrega";
	private String html;

	public Descarrega()
	{
		html = "";
	}

	public long descarregarguardar(String url, String path) throws IOException
	{
		// Descarrega un arxiu i el guarda
		// Creem l'arxiu
		File file = new File(path + url.substring(url.lastIndexOf("/")+1, url.length()));
		// Iniciem la descarrega

		URLConnection conn = new URL(url).openConnection();
		conn.connect();
		Log.d(TAG, "\nDescarregant: \n");
		Log.d(TAG, " >> URL: " + url + " >> Desti: " + path + " >> Tamany: "
				+ conn.getContentLength() + " bytes");
		// Llegeix cada byte i l'escriu en un arxiu fins que arriba a -1
		InputStream in = conn.getInputStream();
		OutputStream out = new FileOutputStream(file);
		int b = 0;
		while (b != -1)
		{
			b = in.read();
			if (b != -1)
			{
				out.write(b);
			}
		}
		out.close();
		in.close();
		return conn.getContentLength();
	}

	protected String doInBackground(String url) throws IOException
	{
		// Descarrega un arxiu i el retorna en un String
		html = "";
		// Iniciem la connexi� i creem els Streams
		URLConnection conn = new URL(url).openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		// Iniciem la descarrega i anem guardant al String
		Log.d(TAG, "\nDescarregant: \n");
		Log.d(TAG, ">> URL: " + url + " >> Tamany: " + conn.getContentLength()
				+ " bytes");
		String inputLine;
		while ((inputLine = in.readLine()) != null)
		{
			html = html + "\n" + inputLine;
		}
		Log.d(TAG, "Descarrega finalitzada");
		in.close();
		return html;
	}

	@Override
	protected Object doInBackground(Object... arg0)
	{
		// Metode Overrided, no te utilitat
		return null;
	}
}