[BAEL-19087]-Move articles out of core-java-io part 2

This commit is contained in:
catalin-burcea
2019-11-09 01:09:41 +02:00
parent 6976e5dedf
commit b967135f2f
37 changed files with 195 additions and 220 deletions

View File

@@ -0,0 +1,75 @@
package com.baeldung.bufferedreader;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
public class BufferedReaderExampleUnitTest {
private static final String FILE_PATH = "src/main/resources/input.txt";
@Test
public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readAllLines(reader);
assertThat(content).isNotEmpty();
assertThat(content).contains("Lorem ipsum");
}
@Test
public void givenBufferedReader_whenReadAllLinesWithStream_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readAllLinesWithStream(reader);
assertThat(content).isNotEmpty();
assertThat(content).contains("Lorem ipsum");
}
@Test
public void whenReadFile_thenReturnsContent() {
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readFile();
assertThat(content.toString()).contains("Lorem ipsum");
}
@Test
public void givenBufferedReader_whenReadAllCharsOneByOne_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readAllCharsOneByOne(reader);
assertThat(content).isNotEmpty();
assertThat(content).contains("Lorem ipsum");
}
@Test
public void givenBufferedReader_whenReadMultipleChars_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readMultipleChars(reader);
assertThat(content).isNotEmpty();
assertThat(content).isEqualTo("Lorem");
}
@Test
public void whenReadFileTryWithResources_thenReturnsContent() {
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readFileTryWithResources();
assertThat(content.toString()).contains("Lorem ipsum");
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.bufferedreader;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.*;
public class BufferedReaderUnitTest {
private static final String FILE_PATH = "src/main/resources/input.txt";
@Test
public void givenBufferedReader_whenSkipUnderscores_thenOk() throws IOException {
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new StringReader("1__2__3__4__5"))) {
int value;
while((value = reader.read()) != -1) {
result.append((char) value);
reader.skip(2L);
}
}
assertEquals("12345", result.toString());
}
@Test
public void givenBufferedReader_whenSkipsWhitespacesAtBeginning_thenOk() throws IOException {
String result;
try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) {
do {
reader.mark(1);
} while(Character.isWhitespace(reader.read()));
reader.reset();
result = reader.readLine();
}
assertEquals("Lorem ipsum dolor sit amet.", result);
}
@Test
public void whenCreatesNewBufferedReader_thenOk() throws IOException {
try(BufferedReader reader = Files.newBufferedReader(Paths.get(FILE_PATH))) {
assertNotNull(reader);
assertTrue(reader.ready());
}
}
}

View File

@@ -0,0 +1,202 @@
package com.baeldung.file;
import org.junit.Test;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class FileClassUnitTest {
@Test
public void givenDir_whenMkdir_thenDirIsDeleted() {
File directory = new File("dir");
assertTrue(directory.mkdir());
assertTrue(directory.delete());
}
@Test
public void givenFile_whenCreateNewFile_thenFileIsDeleted() {
File file = new File("file.txt");
try {
assertTrue(file.createNewFile());
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
assertTrue(file.delete());
}
@Test
public void givenFile_whenCreateNewFile_thenMetadataIsCorrect() {
String sep = File.separator;
File parentDir = makeDir("filesDir");
File child = new File(parentDir, "file.txt");
try {
child.createNewFile();
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
assertEquals("file.txt", child.getName());
assertEquals(parentDir.getName(), child.getParentFile().getName());
assertEquals(parentDir.getPath() + sep + "file.txt", child.getPath());
removeDir(parentDir);
}
@Test
public void givenReadOnlyFile_whenCreateNewFile_thenCantModFile() {
File parentDir = makeDir("readDir");
File child = new File(parentDir, "file.txt");
try {
child.createNewFile();
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
child.setWritable(false);
boolean writable = true;
try (FileOutputStream fos = new FileOutputStream(child)) {
fos.write("Hello World".getBytes()); // write operation
fos.flush();
} catch (IOException e) {
writable = false;
} finally {
removeDir(parentDir);
}
assertFalse(writable);
}
@Test
public void givenWriteOnlyFile_whenCreateNewFile_thenCantReadFile() {
File parentDir = makeDir("writeDir");
File child = new File(parentDir, "file.txt");
try {
child.createNewFile();
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
child.setReadable(false);
boolean readable = true;
try (FileInputStream fis = new FileInputStream(child)) {
fis.read(); // read operation
} catch (IOException e) {
readable = false;
} finally {
removeDir(parentDir);
}
assertFalse(readable);
}
@Test
public void givenFilesInDir_whenCreateNewFile_thenCanListFiles() {
File parentDir = makeDir("filtersDir");
String[] files = {"file1.csv", "file2.txt"};
for (String file : files) {
try {
new File(parentDir, file).createNewFile();
} catch (IOException e) {
fail("Could not create " + file);
}
}
//normal listing
assertEquals(2, parentDir.list().length);
//filtered listing
FilenameFilter csvFilter = (dir, ext) -> ext.endsWith(".csv");
assertEquals(1, parentDir.list(csvFilter).length);
removeDir(parentDir);
}
@Test
public void givenDir_whenMkdir_thenCanRenameDir() {
File source = makeDir("source");
File destination = makeDir("destination");
boolean renamed = source.renameTo(destination);
if (renamed) {
assertFalse(source.isDirectory());
assertTrue(destination.isDirectory());
removeDir(destination);
}
}
@Test
public void givenDataWritten_whenWrite_thenFreeSpaceReduces() {
String home = System.getProperty("user.home");
String sep = File.separator;
File testDir = makeDir(home + sep + "test");
File sample = new File(testDir, "sample.txt");
long freeSpaceBefore = testDir.getFreeSpace();
try {
writeSampleDataToFile(sample);
} catch (IOException e) {
fail("Could not write to " + "sample.txt");
}
long freeSpaceAfter = testDir.getFreeSpace();
assertTrue(freeSpaceAfter < freeSpaceBefore);
removeDir(testDir);
}
private static File makeDir(String name) {
File directory = new File(name);
directory.mkdir();
if (directory.isDirectory()) {
return directory;
}
throw new RuntimeException("'" + name + "' not made!");
}
private static void removeDir(File directory) {
// make sure you don't delete your home directory here
String home = System.getProperty("user.home");
if (directory.getPath().equals(home)) {
return;
}
// remove directory and its files from system
if (directory.exists()) {
// delete all files inside the directory
File[] dirFiles = directory.listFiles();
if (dirFiles != null) {
List<File> files = Arrays.asList(dirFiles);
files.forEach(f -> deleteFile(f));
}
// finally delete the directory itself
deleteFile(directory);
}
}
private static void deleteFile(File fileToDelete) {
if (fileToDelete != null && fileToDelete.exists()) {
fileToDelete.delete();
}
}
private static void writeSampleDataToFile(File sample) throws IOException {
//write sample text to file
try (FileOutputStream out = new FileOutputStream(sample)) {
for (int i = 1; i <= 100000; i++) {
String text = "Sample line number " + i + "\n";
out.write(text.getBytes());
}
}
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.filenamefilter;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class FilenameFilterManualTest {
private static File directory;
@BeforeClass
public static void setupClass() {
directory = new File(FilenameFilterManualTest.class.getClassLoader()
.getResource("fileNameFilterManualTestFolder")
.getFile());
}
@Test
public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() {
FilenameFilter filter = (dir, name) -> name.endsWith(".json");
String[] expectedFiles = { "people.json", "students.json" };
String[] actualFiles = directory.list(filter);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
@Test
public void whenFilteringFilesEndingWithXml_thenEqualExpectedFiles() {
Predicate<String> predicate = (name) -> name.endsWith(".xml");
String[] expectedFiles = { "teachers.xml", "workers.xml" };
List<String> files = Arrays.stream(directory.list())
.filter(predicate)
.collect(Collectors.toList());
String[] actualFiles = files.toArray(new String[files.size()]);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
}

View File

@@ -0,0 +1,99 @@
package com.baeldung.filepath;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class JavaFilePathUnitTest {
private static String userDir;
@BeforeClass
public static void createFilesAndFolders() throws IOException {
userDir = System.getProperty("user.dir");
new File(userDir + "/baeldung/foo").mkdirs();
new File(userDir + "/baeldung/bar/baz").mkdirs();
new File(userDir + "/baeldung/foo/foo-one.txt").createNewFile();
new File(userDir + "/baeldung/foo/foo-two.txt").createNewFile();
new File(userDir + "/baeldung/bar/bar-one.txt").createNewFile();
new File(userDir + "/baeldung/bar/bar-two.txt").createNewFile();
new File(userDir + "/baeldung/bar/baz/baz-one.txt").createNewFile();
new File(userDir + "/baeldung/bar/baz/baz-two.txt").createNewFile();
}
@Test
public void whenPathResolved_thenSuccess() {
File file = new File("baeldung/foo/foo-one.txt");
String expectedPath = isWindows() ? "baeldung\\foo\\foo-one.txt" : "baeldung/foo/foo-one.txt";
String actualPath = file.getPath();
assertEquals(expectedPath, actualPath);
}
@Test
public void whenAbsolutePathResolved_thenSuccess() {
File file = new File("baeldung/foo/foo-one.txt");
String expectedPath = isWindows() ? userDir + "\\baeldung\\foo\\foo-one.txt" : userDir + "/baeldung/foo/foo-one.txt";
String actualPath = file.getAbsolutePath();
assertEquals(expectedPath, actualPath);
}
@Test
public void whenAbsolutePathWithShorthandResolved_thenSuccess() {
File file = new File("baeldung/bar/baz/../bar-one.txt");
String expectedPath = isWindows() ? userDir + "\\baeldung\\bar\\baz\\..\\bar-one.txt" : userDir + "/baeldung/bar/baz/../bar-one.txt";
String actualPath = file.getAbsolutePath();
assertEquals(expectedPath, actualPath);
}
@Test
public void whenCanonicalPathWithShorthandResolved_thenSuccess() throws IOException {
File file = new File("baeldung/bar/baz/../bar-one.txt");
String expectedPath = isWindows() ? userDir + "\\baeldung\\bar\\bar-one.txt" : userDir + "/baeldung/bar/bar-one.txt";
String actualPath = file.getCanonicalPath();
assertEquals(expectedPath, actualPath);
}
@Test
public void whenCanonicalPathWithDotShorthandResolved_thenSuccess() throws IOException {
File file = new File("baeldung/bar/baz/./baz-one.txt");
String expectedPath = isWindows() ? userDir + "\\baeldung\\bar\\baz\\baz-one.txt" : userDir + "/baeldung/bar/baz/baz-one.txt";
String actualPath = file.getCanonicalPath();
assertEquals(expectedPath, actualPath);
}
@Test(expected = IOException.class)
public void givenWindowsOs_whenCanonicalPathWithWildcard_thenIOException() throws IOException {
Assume.assumeTrue(isWindows());
new File("*").getCanonicalPath();
}
@AfterClass
public static void deleteFilesAndFolders() {
File baeldungDir = new File(userDir + "/baeldung");
deleteRecursively(baeldungDir);
}
private static void deleteRecursively(File dir) {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
deleteRecursively(f);
}
f.delete();
}
dir.delete();
}
private static boolean isWindows() {
String osName = System.getProperty("os.name");
return osName.contains("Windows");
}
}

View File

@@ -0,0 +1,50 @@
package com.baeldung.filereader;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExampleUnitTest {
private static final String FILE_PATH = "src/test/resources/HelloWorld.txt";
@Test
public void givenFileReader_whenReadAllCharacters_thenReturnsContent() throws IOException {
String expectedText = "Hello, World!";
File file = new File(FILE_PATH);
try (FileReader fileReader = new FileReader(file)) {
String content = FileReaderExample.readAllCharactersOneByOne(fileReader);
Assert.assertEquals(expectedText, content);
}
}
@Test
public void givenFileReader_whenReadMultipleCharacters_thenReturnsContent() throws IOException {
String expectedText = "Hello";
File file = new File(FILE_PATH);
try (FileReader fileReader = new FileReader(file)) {
String content = FileReaderExample.readMultipleCharacters(fileReader, 5);
Assert.assertEquals(expectedText, content);
}
}
@Test
public void whenReadFile_thenReturnsContent() {
String expectedText = "Hello, World!";
String content = FileReaderExample.readFile(FILE_PATH);
Assert.assertEquals(expectedText, content);
}
@Test
public void whenReadFileUsingTryWithResources_thenReturnsContent() {
String expectedText = "Hello, World!";
String content = FileReaderExample.readFileUsingTryWithResources(FILE_PATH);
Assert.assertEquals(expectedText, content);
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.filewriter;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileWriterExampleUnitTest {
@After
public void tearDown() throws IOException {
Files.delete(Paths.get("src/test/resources/FileWriterTest.txt"));
}
@Test
public void testWriteString() throws IOException {
try (FileWriter fileWriter = new FileWriter("src/test/resources/FileWriterTest.txt")) {
fileWriter.write("Hello Folks!");
}
Assert.assertEquals("Hello Folks!", new String(Files.readAllBytes(Paths.get("src/test/resources/FileWriterTest.txt"))));
}
@Test
public void testAppendString() throws IOException {
try (FileWriter fileWriter = new FileWriter("src/test/resources/FileWriterTest.txt")) {
fileWriter.write("Hello Folks!");
}
// using another try with resources to reopen the file in append mode
try (FileWriter fileWriter = new FileWriter("src/test/resources/FileWriterTest.txt", true)) {
fileWriter.write("Hello Folks Again!");
}
Assert.assertEquals("Hello Folks!" + "Hello Folks Again!", new String(Files.readAllBytes(Paths.get("src/test/resources/FileWriterTest.txt"))));
}
@Test
public void testWriteCharArray() throws IOException {
try (FileWriter fileWriter = new FileWriter("src/test/resources/FileWriterTest.txt")) {
fileWriter.write("Hello Folks!".toCharArray());
}
Assert.assertEquals("Hello Folks!", new String(Files.readAllBytes(Paths.get("src/test/resources/FileWriterTest.txt"))));
}
}

View File

@@ -0,0 +1,76 @@
package com.baeldung.outputstream;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertTrue;
public class OutputStreamExamplesUnitTest {
StringBuilder filePath = new StringBuilder();
@Before
public void init() {
filePath.append("src");
filePath.append(File.separator);
filePath.append("test");
filePath.append(File.separator);
filePath.append("resources");
filePath.append(File.separator);
filePath.append("output_file.txt");
}
@Test
public void givenOutputStream_whenWriteSingleByteCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSingle(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStream_whenWriteByteSequenceCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSequence(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStream_whenWriteByteSubSequenceCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSubSequence(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenBufferedOutputStream_whenCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.bufferedOutputStream(filePath.toString(), "Hello", "World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStreamWriter_whenCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.outputStreamWriter(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
}

View File

@@ -0,0 +1,178 @@
package com.baeldung.scanner;
import org.junit.Test;
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
import static org.junit.Assert.*;
public class JavaScannerUnitTest {
@Test
public void whenReadFileWithScanner_thenCorrect() throws IOException {
final Scanner scanner = new Scanner(new File("src/test/resources/test_read.in"));
assertTrue(scanner.hasNext());
assertEquals("Hello", scanner.next());
assertEquals("world", scanner.next());
scanner.close();
}
@Test
public void whenConvertInputStreamToString_thenConverted() throws IOException {
final String expectedValue = "Hello world";
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
final Scanner scanner = new Scanner(inputStream);
scanner.useDelimiter("\\A");
final String result = scanner.next();
assertEquals(expectedValue, result);
scanner.close();
}
@Test
public void whenReadUsingBufferedReader_thenCorrect() throws IOException {
final String firstLine = "Hello world";
final String secondLine = "Hi, John";
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read_multiple.in"));
String result = reader.readLine();
assertEquals(firstLine, result);
result = reader.readLine();
assertEquals(secondLine, result);
reader.close();
}
@Test
public void whenReadUsingScanner_thenCorrect() throws IOException {
final String firstLine = "Hello world";
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read_multiple.in");
final Scanner scanner = new Scanner(inputStream);
final String result = scanner.nextLine();
assertEquals(firstLine, result);
scanner.useDelimiter(", ");
assertEquals("Hi", scanner.next());
assertEquals("John", scanner.next());
scanner.close();
}
@Test
public void whenReadingInputFromConsole_thenCorrect() {
final String input = "Hello";
final InputStream stdin = System.in;
System.setIn(new ByteArrayInputStream(input.getBytes()));
final Scanner scanner = new Scanner(System.in);
final String result = scanner.next();
assertEquals(input, result);
System.setIn(stdin);
scanner.close();
}
@Test
public void whenValidateInputUsingScanner_thenValidated() throws IOException {
final String input = "2000";
final InputStream stdin = System.in;
System.setIn(new ByteArrayInputStream(input.getBytes()));
final Scanner scanner = new Scanner(System.in);
final boolean isIntInput = scanner.hasNextInt();
assertTrue(isIntInput);
System.setIn(stdin);
scanner.close();
}
@Test
public void whenScanString_thenCorrect() throws IOException {
final String input = "Hello 1 F 3.5";
final Scanner scanner = new Scanner(input);
scanner.useLocale(Locale.US);
assertEquals("Hello", scanner.next());
assertEquals(1, scanner.nextInt());
assertEquals(15, scanner.nextInt(16));
assertEquals(3.5, scanner.nextDouble(), 0.00000001);
scanner.close();
}
@Test
public void whenFindPatternUsingScanner_thenFound() throws IOException {
final String expectedValue = "world";
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
final Scanner scanner = new Scanner(inputStream);
final String result = scanner.findInLine("wo..d");
assertEquals(expectedValue, result);
scanner.close();
}
@Test
public void whenFindPatternInHorizon_thenFound() throws IOException {
final String expectedValue = "world";
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
final Scanner scanner = new Scanner(inputStream);
String result = scanner.findWithinHorizon("wo..d", 5);
assertNull(result);
result = scanner.findWithinHorizon("wo..d", 100);
assertEquals(expectedValue, result);
scanner.close();
}
@Test
public void whenSkipPatternUsingScanner_thenSkiped() throws IOException {
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
final Scanner scanner = new Scanner(inputStream);
scanner.skip(".e.lo");
assertEquals("world", scanner.next());
scanner.close();
}
@Test
public void whenChangeScannerDelimiter_thenChanged() throws IOException {
final String expectedValue = "Hello world";
final String[] splited = expectedValue.split("o");
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
final Scanner scanner = new Scanner(inputStream);
scanner.useDelimiter("o");
assertEquals(splited[0], scanner.next());
assertEquals(splited[1], scanner.next());
assertEquals(splited[2], scanner.next());
scanner.close();
}
@Test
public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException {
final Scanner scanner = new Scanner(new File("src/test/resources/test_read_d.in"));
scanner.useDelimiter(",|-");
assertEquals("John", scanner.next());
assertEquals("Adam", scanner.next());
assertEquals("Tom", scanner.next());
scanner.close();
}
}

View File

@@ -0,0 +1 @@
Hello, World!

View File

@@ -0,0 +1 @@
Hello world

View File

@@ -0,0 +1 @@
John,Adam-Tom

View File

@@ -0,0 +1,2 @@
Hello world
Hi, John