-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataScraper.java
More file actions
109 lines (93 loc) · 3.04 KB
/
DataScraper.java
File metadata and controls
109 lines (93 loc) · 3.04 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
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
public class DataScraper {
public static class Scraper implements Runnable {
String url, path;
public Scraper(String url, String path) {
this.url = url;
this.path = path;
}
@Override
public void run() {
try {
Console.progress(1);
if (!ReadWrite.exists(path))
DataScraper.writeWebPage(url, path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeWebPage(String url, String absolute_path) throws IOException {
InputStream in = new URL(url).openStream();
Files.copy(in, Paths.get(absolute_path));
in.close();
}
public static String downloadWebPage(String webpage)
{
String html = null;
try {
// Create URL object
URL url = new URL(webpage);
BufferedReader readr = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
// read each line from stream till end
String line;
while ((line = readr.readLine()) != null) {
html += line;
}
readr.close();
}
// Exceptions
catch (MalformedURLException mue) {
System.out.println("Malformed URL Exception raised");
}
catch (IOException ie) {
System.out.println("IOException raised");
}
return html;
}
public static String downloadWebPage(String webpage, String charset)
{
String html = null;
try {
// Create URL object
URL url = new URL(webpage);
BufferedReader readr = new BufferedReader(new InputStreamReader(url.openStream(), charset));
// read each line from stream till end
String line;
while ((line = readr.readLine()) != null) {
html += line;
}
readr.close();
}
// Exceptions
catch (MalformedURLException mue) {
System.out.println("Malformed URL Exception raised");
}
catch (IOException ie) {
System.out.println("IOException raised");
}
return html;
}
public static byte[] downloadImage(String webUrl) throws IOException {
URL url = new URL(webUrl);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
return out.toByteArray();
}
}