Added the code for "The difference between BufferedReader and FileReader". (#13942)
This commit is contained in:
parent
078826eef5
commit
23ec3d24d2
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.bufferedreadervsfilereader;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class BufferedReaderUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReadingAFile_thenReadsLineByLine() {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
|
||||||
|
try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
|
||||||
|
String line;
|
||||||
|
|
||||||
|
while((line = br.readLine()) != null) {
|
||||||
|
result.append(line);
|
||||||
|
result.append('\n');
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.bufferedreadervsfilereader;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class FileReaderUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReadingAFile_thenReadsCharByChar() {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
|
||||||
|
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||||
|
int i = fr.read();
|
||||||
|
|
||||||
|
while(i != -1) {
|
||||||
|
result.append((char)i);
|
||||||
|
|
||||||
|
i = fr.read();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("qwerty", result.toString());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
first line
|
||||||
|
second line
|
||||||
|
third line
|
|
@ -0,0 +1 @@
|
||||||
|
qwerty
|
Loading…
Reference in New Issue