This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,3 @@
# Intellij
.idea/
*.iml
@@ -0,0 +1,6 @@
### 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)
+279
View File
@@ -0,0 +1,279 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-io-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${moneta.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>${async-http-client.version}</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>test</scope>
</dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<opencsv.version>4.1</opencsv.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<hsqldb.version>2.4.0</hsqldb.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<async-http-client.version>2.4.5</async-http-client.version>
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
</properties>
</project>
@@ -0,0 +1,57 @@
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;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.createfiles;
import com.google.common.io.Files;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CreateFilesUnitTest {
@Test
public void givenAnExistingDirectory_whenCreatingAFileWithAbsolutePath_thenFileIsCreated() throws IOException {
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File fileWithAbsolutePath = new File(tempDirectory.getAbsolutePath() + "/myDirectory/testFile.txt");
assertFalse(fileWithAbsolutePath.exists());
Files.touch(fileWithAbsolutePath);
assertTrue(fileWithAbsolutePath.exists());
}
@Test
public void givenAnExistingDirectory_whenCreatingANewDirectoryAndFileWithRelativePath_thenFileIsCreated() throws IOException {
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File fileWithRelativePath = new File(tempDirectory, "myDirectory/newFile.txt");
assertFalse(fileWithRelativePath.exists());
Files.touch(fileWithRelativePath);
assertTrue(fileWithRelativePath.exists());
}
@Test
public void whenCreatingAFileWithFileSeparator_thenFileIsCreated() throws IOException {
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File newFile = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile.txt");
assertFalse(newFile.exists());
Files.touch(newFile);
assertTrue(newFile.exists());
}
}
@@ -0,0 +1,179 @@
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 givenDirectoryCreated_whenMkdirIsInvoked_thenDirectoryIsDeleted() {
File directory = new File("testDirectory");
if (!directory.isDirectory() || !directory.exists()) {
directory.mkdir();
}
assertTrue(directory.delete());
}
@Test
public void givenFileCreated_whenCreateNewFileIsInvoked_thenFileIsDeleted() throws IOException {
File file = new File("testFile.txt");
if (!file.isFile() || !file.exists()) {
file.createNewFile();
}
assertTrue(file.delete());
}
@Test
public void givenFileCreated_whenCreateNewFileInvoked_thenMetadataIsAsExpected() throws IOException {
// different Operating systems have different separator characters
String separatorCharacter = System.getProperty("file.separator");
File parentDirectory = makeDirectory("filesDirectory");
File childFile = new File(parentDirectory, "file1.txt");
childFile.createNewFile();
assertTrue(childFile.getName().equals("file1.txt"));
assertTrue(childFile.getParentFile().getName().equals(parentDirectory.getName()));
assertTrue(childFile.getPath().equals(parentDirectory.getPath() + separatorCharacter + "file1.txt"));
removeDirectory(parentDirectory);
}
@Test(expected = FileNotFoundException.class)
public void givenReadOnlyFileCreated_whenCreateNewFileInvoked_thenFileCannotBeWrittenTo() throws IOException {
File parentDirectory = makeDirectory("filesDirectory");
File childFile = new File(parentDirectory, "file1.txt");
childFile.createNewFile();
childFile.setWritable(false);
FileOutputStream fos = new FileOutputStream(childFile);
fos.write("Hello World".getBytes()); // write operation
fos.flush();
fos.close();
removeDirectory(parentDirectory);
}
@Test(expected = FileNotFoundException.class)
public void givenWriteOnlyFileCreated_whenCreateNewFileInvoked_thenFileCannotBeReadFrom() throws IOException {
File parentDirectory = makeDirectory("filesDirectory");
File childFile = new File(parentDirectory, "file1.txt");
childFile.createNewFile();
childFile.setReadable(false);
FileInputStream fis = new FileInputStream(childFile);
fis.read(); // read operation
fis.close();
removeDirectory(parentDirectory);
}
@Test
public void givenFilesCreatedInDirectory_whenCreateNewFileInvoked_thenTheyCanBeListedAsExpected() throws IOException {
File directory = makeDirectory("filtersDirectory");
File csvFile = new File(directory, "csvFile.csv");
csvFile.createNewFile();
File txtFile = new File(directory, "txtFile.txt");
txtFile.createNewFile();
//normal listing
assertEquals(2, directory.list().length);
//filtered listing
FilenameFilter csvFilter = (dir, ext) -> ext.endsWith(".csv");
assertEquals(1, directory.list(csvFilter).length);
removeDirectory(directory);
}
@Test
public void givenDirectoryIsCreated_whenMkdirInvoked_thenDirectoryCanBeRenamed() {
File source = makeDirectory("source");
File destination = makeDirectory("destination");
source.renameTo(destination);
assertFalse(source.isDirectory());
assertTrue(destination.isDirectory());
removeDirectory(destination);
}
@Test
public void givenDataIsWrittenToFile_whenWriteIsInvoked_thenFreeSpaceOnSystemDecreases() throws IOException {
String name = System.getProperty("user.home") + System.getProperty("file.separator") + "test";
File testDir = makeDirectory(name);
File sample = new File(testDir, "sample.txt");
long freeSpaceBeforeWrite = testDir.getFreeSpace();
writeSampleDataToFile(sample);
long freeSpaceAfterWrite = testDir.getFreeSpace();
assertTrue(freeSpaceAfterWrite < freeSpaceBeforeWrite);
removeDirectory(testDir);
}
private static File makeDirectory(String directoryName) {
File directory = new File(directoryName);
directory.mkdir();
if (directory.isDirectory()) {
return directory;
}
throw new RuntimeException("Directory not created for " + directoryName);
}
private static void removeDirectory(File directory) {
// make sure you don't delete your home directory here
if (directory.getPath().equals(System.getProperty("user.home"))) {
return;
}
// remove directory and its files from system
if (directory != null && directory.exists()) {
// delete all files inside the directory
File[] filesInDirectory = directory.listFiles();
if (filesInDirectory != null) {
List<File> files = Arrays.asList(filesInDirectory);
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 sampleText = "Sample line number " + i + "\n";
out.write(sampleText.getBytes());
}
}
}
}
@@ -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);
}
}
@@ -0,0 +1,47 @@
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"))));
}
}
@@ -0,0 +1 @@
Hello, World!