-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathRScriptReader.java
More file actions
64 lines (54 loc) · 1.62 KB
/
Copy pathRScriptReader.java
File metadata and controls
64 lines (54 loc) · 1.62 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
package rprocessing.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* RScriptReader Read the script from r package.
*
* @author github.com/gaocegege
*/
public class RScriptReader {
private static final Charset UTF8 = Charset.forName("utf-8");
public static class ResourceReader {
private final Class<?> clazz;
public ResourceReader(final Class<?> clazz) {
this.clazz = clazz;
}
public String readText(final String resource) {
return RScriptReader.readResourceAsText(clazz, resource);
}
}
/**
* read the resource as text
*
* @param clazz
* @param resource
* @return
*/
public static String readResourceAsText(final Class<?> clazz, final String resource) {
try (final InputStream in = clazz.getResourceAsStream(resource)) {
return readText(in);
} catch (final IOException exception) {
throw new RuntimeException(exception);
}
}
public static String readText(final InputStream in) throws IOException {
return new String(readFully(in), UTF8);
}
public static String readText(final Path path) throws IOException {
return new String(Files.readAllBytes(path), UTF8);
}
public static byte[] readFully(final InputStream in) throws IOException {
try (final ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024)) {
final byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) {
bytes.write(buf, 0, n);
}
return bytes.toByteArray();
}
}
}