Added the code for "The difference between BufferedReader and FileReader". (#13942)

This commit is contained in:
Arya 2023-05-04 00:52:17 +03:00 committed by GitHub
parent 078826eef5
commit 23ec3d24d2
4 changed files with 65 additions and 0 deletions

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -0,0 +1,3 @@
first line
second line
third line