forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloadFile.java
More file actions
39 lines (36 loc) · 1.33 KB
/
DownloadFile.java
File metadata and controls
39 lines (36 loc) · 1.33 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
package com.examplehub.basics.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class DownloadFile {
public static boolean solution1(String url, String to) throws MalformedURLException {
try (BufferedInputStream bufferedInputStream =
new BufferedInputStream(new URL(url).openStream())) {
BufferedOutputStream bufferedOutputStream =
new BufferedOutputStream(new FileOutputStream(to));
byte[] bytes = new byte[1024];
int readBytes;
while ((readBytes = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, readBytes);
bufferedOutputStream.flush();
}
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean solution2(String url, String to) throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(url).openStream());
Files.copy(bufferedInputStream, Paths.get(to), StandardCopyOption.REPLACE_EXISTING);
bufferedInputStream.close();
return true;
}
}