11package org .baeldung .java ;
22
3+ import java .io .File ;
4+ import java .io .FileInputStream ;
5+ import java .io .IOException ;
6+ import java .util .Scanner ;
7+
8+ import org .apache .commons .io .FileUtils ;
39import org .junit .Test ;
10+ import org .slf4j .Logger ;
11+ import org .slf4j .LoggerFactory ;
12+
13+ import com .google .common .base .Charsets ;
14+ import com .google .common .io .Files ;
415
516public class CoreJavaIoUnitTest {
17+ protected final Logger logger = LoggerFactory .getLogger (getClass ());
618
719 // tests -
820
921 @ Test
10- public final void whenIteratingAFile_thenCorrect () {
11- //
22+ public final void givenUsingGuava_whenIteratingAFile_thenCorrect () throws IOException {
23+ final String path = "G:\\ full\\ train\\ input\\ " + "trainDataNegative.csv" ;
24+ // final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
25+
26+ logMemory ();
27+ Files .readLines (new File (path ), Charsets .UTF_8 );
28+ logMemory ();
29+ }
30+
31+ @ Test
32+ public final void givenUsingCommonsIo_whenIteratingAFile_thenCorrect () throws IOException {
33+ final String path = "G:\\ full\\ train\\ input\\ " + "trainDataNegative.csv" ;
34+ // final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
35+
36+ logMemory ();
37+ FileUtils .readLines (new File (path ));
38+ logMemory ();
39+ }
40+
41+ @ Test
42+ public final void whenStreamingThroughAFile_thenCorrect () throws IOException {
43+ final String path = "G:\\ full\\ train\\ input\\ " + "trainDataNegative.csv" ;
44+ // final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
45+
46+ logMemory ();
47+
48+ FileInputStream inputStream = null ;
49+ Scanner sc = null ;
50+ try {
51+ inputStream = new FileInputStream (path );
52+ sc = new Scanner (inputStream , "UTF-8" );
53+ while (sc .hasNextLine ()) {
54+ final String line = sc .nextLine ();
55+ // System.out.println(line);
56+ }
57+ // note that Scanner suppresses exceptions
58+ if (sc .ioException () != null ) {
59+ throw sc .ioException ();
60+ }
61+ } finally {
62+ if (inputStream != null ) {
63+ inputStream .close ();
64+ }
65+ if (sc != null ) {
66+ sc .close ();
67+ }
68+ }
69+
70+ logMemory ();
71+ }
72+
73+ //
74+
75+ private final void logMemory () {
76+ logger .info ("Max Memory: {} Mb" , Runtime .getRuntime ().maxMemory () / 1048576 );
77+ logger .info ("Total Memory: {} Mb" , Runtime .getRuntime ().totalMemory () / 1048576 );
78+ logger .info ("Free Memory: {} Mb" , Runtime .getRuntime ().freeMemory () / 1048576 );
1279 }
1380
1481}
82+ //
0 commit comments