File tree Expand file tree Collapse file tree
main/java/com/stubbornjava/common
java/com/stubbornjava/common Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package com .stubbornjava .common ;
22
3+ import java .io .BufferedReader ;
34import java .io .IOException ;
45import java .net .URL ;
56
67import com .google .common .base .Charsets ;
8+ import com .google .common .io .CharSource ;
79
810public 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}
Original file line number Diff line number Diff line change 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\n world\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\n world\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+ }
Original file line number Diff line number Diff line change 1+ hello
2+ world
You can’t perform that action at this time.
0 commit comments