Descarrega.java 2.57 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.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

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


public class Descarrega extends AsyncTask<Object, Object, Object>{
	final static String TAG = "Descarrega";
	private String url;
	private String nomarxiu;
	private String carpeta;
	private String html;
	private File arxiu;

	public Descarrega(String url, String nomarxiu, String carpeta) {
		this.url = url;
		this.nomarxiu = nomarxiu;
		this.carpeta = carpeta;
		this.html = null;
		this.arxiu = null;
	}

	public void descarregarguardar() {
		// Creem el directori
		File dir = new File(carpeta);
		if (!dir.exists()) {
			if (!dir.mkdir()) {
				return; // No s'ha pogut crear (ja existeix)
			}
		}

		// Creem l'arxiu
		arxiu = new File(carpeta + nomarxiu);

		// Iniciem la descàrrega
		try {
			URLConnection conn = new URL(url).openConnection();
			conn.connect();
			Log.d(TAG, "\nDescarregant: \n");
			Log.d(TAG, " >> URL: " + url + " >> Nom: " + nomarxiu
					+ " >> 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(arxiu);
			int b = 0;
			while (b != -1) {
				b = in.read();
				if (b != -1) {
					out.write(b);
				}
			}
			out.close();
			in.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	

	protected String doInBackground() {
		try {
			URLConnection conn = new URL(url).openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			Log.d(TAG, "\nDescarregant: \n");
			Log.d(TAG, ">> URL: " + url + " >> Tamany: " + conn.getContentLength() + " bytes");
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				//Log.d(TAG, inputLine);
				html = html + "\n" + inputLine;
			}
			Log.d(TAG, "Descarrega finalitzada");
			
			in.close();
		} catch (MalformedURLException e) {
			Log.d(TAG, "excepcio 1, no sha trobat la URL");
		} catch (IOException e) {
			Log.d(TAG, "excepcio 2");
		}
		
		return html;
		
	
	}
	
	

	@Override
	protected Object doInBackground(Object... arg0) {
		
		return null;
	}
}