-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileUtils.java
More file actions
56 lines (48 loc) · 1.57 KB
/
Copy pathFileUtils.java
File metadata and controls
56 lines (48 loc) · 1.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
package ru.cwcode.cwutils.files;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class FileUtils {
/**
* @return пустую строку, если не удалось прочитать файл или его нет
*/
public static String readString(Path path) {
try {
return Files.readString(path, StandardCharsets.UTF_8);
} catch (IOException ignored) {
}
return "";
}
public static void writeString(Path path, String text) {
try {
if (!Files.exists(path)) {
com.google.common.io.Files.createParentDirs(path.toFile());
}
Files.writeString(path, text, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadFileTo(String source, String destination) throws IOException {
URL url = new URL(source);
InputStream is = url.openStream();
Path destinationPath = Path.of(destination);
if (!Files.exists(destinationPath)) {
com.google.common.io.Files.createParentDirs(destinationPath.toFile());
}
OutputStream os = new FileOutputStream(destinationPath.toFile());
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}