|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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;
|
|
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
|
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");
|
|
51
|
Log.d(TAG, " >> URL: " + url + " >> Nom: " + nomarxiu
|
|
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
+ " >> 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();
}
}
|
|
76
|
protected String doInBackground() {
|
|
77
78
79
80
81
|
try {
URLConnection conn = new URL(url).openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
Log.d(TAG, "\nDescarregant: \n");
|
|
82
|
Log.d(TAG, ">> URL: " + url + " >> Tamany: " + conn.getContentLength() + " bytes");
|
|
83
84
|
String inputLine;
while ((inputLine = in.readLine()) != null) {
|
|
85
|
//Log.d(TAG, inputLine);
|
|
86
|
html = html + "\n" + inputLine;
|
|
87
88
|
}
Log.d(TAG, "Descarrega finalitzada");
|
|
89
|
|
|
90
91
|
in.close();
} catch (MalformedURLException e) {
|
|
92
|
Log.d(TAG, "excepcio 1, no sha trobat la URL");
|
|
93
94
95
96
97
98
99
100
|
} catch (IOException e) {
Log.d(TAG, "excepcio 2");
}
return html;
}
|
|
101
102
|
|
|
103
104
105
106
107
108
109
|
@Override
protected Object doInBackground(Object... arg0) {
return null;
}
}
|