11package com .baeldung .file ;
22
3+ import org .apache .commons .io .FileUtils ;
4+ import org .hamcrest .CoreMatchers ;
5+ import org .hamcrest .Matchers ;
6+ import org .junit .Assert ;
7+ import org .junit .Test ;
8+
39import java .io .BufferedReader ;
410import java .io .File ;
511import java .io .FileInputStream ;
612import java .io .IOException ;
713import java .io .InputStream ;
814import java .io .InputStreamReader ;
15+ import java .net .URISyntaxException ;
916import java .net .URL ;
1017import java .net .URLConnection ;
1118import java .nio .file .Files ;
1219import java .nio .file .Path ;
1320import java .nio .file .Paths ;
14- import java .util .function .Consumer ;
1521import java .util .stream .Stream ;
1622
17- import org .apache .commons .io .FileUtils ;
18- import org .hamcrest .CoreMatchers ;
19- import org .hamcrest .Matchers ;
20- import org .junit .Assert ;
21- import org .junit .Test ;
22-
2323public class FileOperationsTest {
2424
2525 @ Test
@@ -82,12 +82,10 @@ public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
8282 }
8383
8484 @ Test
85- public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData () throws IOException {
85+ public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData () throws IOException , URISyntaxException {
8686 String expectedData = "Hello World from fileTest.txt!!!" ;
87-
88- ClassLoader classLoader = getClass ().getClassLoader ();
89- File file = new File (classLoader .getResource ("fileTest.txt" ).getFile ());
90- Path path = Paths .get (file .getAbsolutePath ());
87+
88+ Path path = Paths .get (getClass ().getClassLoader ().getResource ("fileTest.txt" ).toURI ());
9189
9290 byte [] fileBytes = Files .readAllBytes (path );
9391 String data = new String (fileBytes );
@@ -96,21 +94,14 @@ public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOExc
9694 }
9795
9896 @ Test
99- public void givenFilePath_whenUsingFilesLines_thenFileData () throws IOException {
97+ public void givenFilePath_whenUsingFilesLines_thenFileData () throws IOException , URISyntaxException {
10098 String expectedData = "Hello World from fileTest.txt!!!" ;
101-
102- ClassLoader classLoader = getClass ().getClassLoader ();
103- File file = new File (classLoader .getResource ("fileTest.txt" ).getFile ());
104- Path path = Paths .get (file .getAbsolutePath ());
99+
100+ Path path = Paths .get (getClass ().getClassLoader ().getResource ("fileTest.txt" ).toURI ());
105101
106102 StringBuilder data = new StringBuilder ();
107103 Stream <String > lines = Files .lines (path );
108- lines .forEach (new Consumer <String >() {
109- @ Override
110- public void accept (String line ) {
111- data .append (line ).append ("\n " );
112- }
113- });
104+ lines .forEach (line -> data .append (line ).append ("\n " ));
114105
115106 Assert .assertEquals (expectedData , data .toString ().trim ());
116107 }
0 commit comments