Descarrega.java
2.57 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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;
}
}