[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

@@ -2,6 +2,3 @@
### Relevant Articles:
- [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory)
- [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader)
- [The Java File Class](https://www.baeldung.com/java-io-file)
- [Java FileWriter](https://www.baeldung.com/java-filewriter)

View File

@@ -1,57 +0,0 @@
package com.baeldung.filereader;
import java.io.*;
public class FileReaderExample {
public static String readAllCharactersOneByOne(Reader reader) throws IOException {
StringBuilder content = new StringBuilder();
int nextChar;
while ((nextChar = reader.read()) != -1) {
content.append((char) nextChar);
}
return String.valueOf(content);
}
public static String readMultipleCharacters(Reader reader, int length) throws IOException {
char[] buffer = new char[length];
int charactersRead = reader.read(buffer, 0, length);
if (charactersRead != -1) {
return new String(buffer, 0, charactersRead);
} else {
return "";
}
}
public static String readFile(String path) {
FileReader fileReader = null;
try {
fileReader = new FileReader(path);
return readAllCharactersOneByOne(fileReader);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String readFileUsingTryWithResources(String path) {
try (FileReader fileReader = new FileReader(path)) {
return readAllCharactersOneByOne(fileReader);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -1,202 +0,0 @@
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 FileClassDemoUnitTest {
@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

@@ -1,50 +0,0 @@
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

@@ -1,47 +0,0 @@
package com.baeldung.filewriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
public class FileWriterExampleUnitTest {
@After
public void tearDown() throws IOException {
Files.delete(Path.of("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(Path.of("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(Path.of("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(Path.of("src/test/resources/FileWriterTest.txt"))));
}
}