Descarrega.java
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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 void 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();
}
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;
}
}