Blame view

src/com/upc/pbe/upcnews/Descarrega.java 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
Imanol-Mikel Barba Sabariego authored
16
//Descarrega un arxiu i el guarda o retorna en String
17
18
19
public class Descarrega extends AsyncTask<Object, Object, Object>
{
20
	final static String TAG = "Descarrega";
21
	private String html;
22
23
24
25
	public Descarrega()
	{
		html = "";
26
27
	}
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
	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);
50
51
			}
		}
52
53
54
		out.close();
		in.close();
		return conn.getContentLength();
55
56
	}
57
58
59
	protected String doInBackground(String url) throws IOException
	{
		// Descarrega un arxiu i el retorna en un String
Imanol-Mikel Barba Sabariego authored
60
		html = "";
61
		// Iniciem la connexi� i creem els Streams
Imanol-Mikel Barba Sabariego authored
62
63
		URLConnection conn = new URL(url).openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
64
		// Iniciem la descarrega i anem guardant al String
Imanol-Mikel Barba Sabariego authored
65
		Log.d(TAG, "\nDescarregant: \n");
66
67
		Log.d(TAG, ">> URL: " + url + " >> Tamany: " + conn.getContentLength()
				+ " bytes");
Imanol-Mikel Barba Sabariego authored
68
		String inputLine;
69
70
		while ((inputLine = in.readLine()) != null)
		{
Imanol-Mikel Barba Sabariego authored
71
72
73
74
			html = html + "\n" + inputLine;
		}
		Log.d(TAG, "Descarrega finalitzada");
		in.close();
75
76
77
78
		return html;
	}

	@Override
79
80
81
	protected Object doInBackground(Object... arg0)
	{
		// Metode Overrided, no te utilitat
82
83
84
		return null;
	}
}