-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathUtils.java
More file actions
96 lines (81 loc) 路 2.42 KB
/
Copy pathUtils.java
File metadata and controls
96 lines (81 loc) 路 2.42 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
package express.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.security.SecureRandom;
public final class Utils {
private Utils() {}
/**
* Write all data from an InputStream in an String
*
* @param is The source InputStream
* @return The data as string
*/
public static String streamToString(InputStream is) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (IOException ignored) {
}
return null;
}
/**
* Returns the MIME-Type of an file.
*
* @param file The file.
* @return The MIME-Type.
*/
public static MediaType getContentType(Path file) {
String ex = getExtension(file);
MediaType contentType = MediaType.getByExtension(ex);
if (contentType == null) {
return MediaType._bin;
}
return contentType;
}
/**
* Generates an random token with SecureRandom
*
* @param byteLength The token length
* @param radix The base
* @return An token with the base of radix
*/
public static String randomToken(int byteLength, int radix) {
SecureRandom secureRandom = new SecureRandom();
byte[] token = new byte[byteLength];
secureRandom.nextBytes(token);
return new BigInteger(1, token).toString(radix); //hex encoding
}
/**
* @return Your ip.
* @throws UnknownHostException If resolving fails
*/
public static String getYourIp() throws UnknownHostException {
return Inet4Address.getLocalHost().getHostAddress();
}
/**
* Extract the extension from the file.
*
* @param file The file.
* @return The extension.
*/
public static String getExtension(Path file) {
String path = file.getFileName().toString();
int index = path.lastIndexOf('.') + 1;
// No extension present
if (index == 0) {
return null;
}
return path.substring(index);
}
}