1+ package com .baeldung .file ;
2+
3+ import org .hamcrest .Matchers ;
4+ import org .junit .Assert ;
5+ import org .junit .Test ;
6+
7+ import java .io .BufferedReader ;
8+ import java .io .IOException ;
9+ import java .io .InputStream ;
10+ import java .io .InputStreamReader ;
11+ import java .net .URL ;
12+ import java .net .URLConnection ;
13+
14+ import static org .hamcrest .CoreMatchers .containsString ;
15+
16+ public class FileOperationsTest {
17+
18+ @ Test
19+ public void givenFileName_whenUsingClassloader_thenFileData () throws IOException {
20+ String expectedData = "Hello World from fileTest.txt!!!" ;
21+
22+ ClassLoader classLoader = getClass ().getClassLoader ();
23+ InputStream inputStream = classLoader .getResourceAsStream ("fileTest.txt" );
24+ String data = readFromInputStream (inputStream );
25+
26+ Assert .assertThat (data , containsString (expectedData ));
27+ }
28+
29+ @ Test
30+ public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData () throws IOException {
31+ String expectedData = "Hello World from fileTest.txt!!!" ;
32+
33+ Class clazz = FileOperationsTest .class ;
34+ InputStream inputStream = clazz .getResourceAsStream ("/fileTest.txt" );
35+ String data = readFromInputStream (inputStream );
36+
37+ Assert .assertThat (data , containsString (expectedData ));
38+ }
39+
40+ @ Test
41+ public void givenURLName_whenUsingURL_thenFileData () throws IOException {
42+ String expectedData = "Baeldung" ;
43+
44+ URL urlObject = new URL ("http://www.baeldung.com/" );
45+ URLConnection urlConnection = urlObject .openConnection ();
46+
47+ InputStream inputStream = urlConnection .getInputStream ();
48+ String data = readFromInputStream (inputStream );
49+
50+ Assert .assertThat (data , containsString (expectedData ));
51+ }
52+
53+ @ Test
54+ public void givenFileName_whenUsingJarFile_thenFileData () throws IOException {
55+ String expectedData = "BSD License" ;
56+
57+ Class clazz = Matchers .class ;
58+ InputStream inputStream = clazz .getResourceAsStream ("/LICENSE.txt" );
59+ String data = readFromInputStream (inputStream );
60+
61+ Assert .assertThat (data , containsString (expectedData ));
62+ }
63+
64+ private String readFromInputStream (InputStream inputStream ) throws IOException {
65+ InputStreamReader inputStreamReader = new InputStreamReader (inputStream );
66+ BufferedReader bufferedReader = new BufferedReader (inputStreamReader );
67+ StringBuilder resultStringBuilder = new StringBuilder ();
68+ String line ;
69+ while ((line = bufferedReader .readLine ()) != null ) {
70+ resultStringBuilder .append (line );
71+ resultStringBuilder .append ("\n " );
72+ }
73+ bufferedReader .close ();
74+ inputStreamReader .close ();
75+ inputStream .close ();
76+ return resultStringBuilder .toString ();
77+ }
78+ }
0 commit comments