Skip to content

Commit 13d66bc

Browse files
committed
Added resource utils and tests
1 parent c93db96 commit 13d66bc

3 files changed

Lines changed: 52 additions & 2 deletions

File tree

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,34 @@
11
package com.stubbornjava.common;
22

3+
import java.io.BufferedReader;
34
import java.io.IOException;
45
import java.net.URL;
56

67
import com.google.common.base.Charsets;
8+
import com.google.common.io.CharSource;
79

810
public class Resources {
911

10-
public static String asString(String path) {
11-
URL url = com.google.common.io.Resources.getResource(path);
12+
// {{start:asString}}
13+
public static String asString(String resource) {
14+
URL url = com.google.common.io.Resources.getResource(resource);
1215
try {
1316
return com.google.common.io.Resources.toString(url, Charsets.UTF_8);
1417
} catch (IOException ex) {
1518
throw new RuntimeException(ex);
1619
}
1720
}
21+
// {{end:asString}}
22+
23+
// {{start:asBufferedReader}}
24+
public static BufferedReader asBufferedReader(String resource) {
25+
URL url = com.google.common.io.Resources.getResource(resource);
26+
try {
27+
CharSource charSource = com.google.common.io.Resources.asCharSource(url, Charsets.UTF_8);
28+
return charSource.openBufferedStream();
29+
} catch (IOException ex) {
30+
throw new RuntimeException(ex);
31+
}
32+
}
33+
// {{end:asBufferedReader}}
1834
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.stubbornjava.common;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.io.BufferedReader;
6+
import java.io.IOException;
7+
8+
import org.junit.Test;
9+
10+
import com.google.common.io.CharStreams;
11+
12+
public class ResourcesTest {
13+
14+
// {{start:asString}}
15+
@Test
16+
public void testAsString() {
17+
String expected = "hello\nworld\n";
18+
String actual = Resources.asString("resources-test/hello.txt");
19+
assertEquals(expected, actual);
20+
}
21+
// {{end:asString}}
22+
23+
// {{start:asBufferedReader}}
24+
@Test
25+
public void testAsBufferedReader() throws IOException {
26+
String expected = "hello\nworld\n";
27+
BufferedReader reader = Resources.asBufferedReader("resources-test/hello.txt");
28+
String actual = CharStreams.toString(reader);
29+
assertEquals(expected, actual);
30+
}
31+
// {{end:asBufferedReader}}
32+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
hello
2+
world

0 commit comments

Comments
 (0)