[BAEL-19088] - Move articles out of core-java-io part 3

This commit is contained in:
catalin-burcea
2019-11-15 11:49:14 +02:00
parent 0950c53112
commit 5ec3630590
95 changed files with 114 additions and 180090 deletions

View File

@@ -1,3 +1,5 @@
# Intellij
.idea/
*.iml
0.*
# Files generated by integration tests
# *.txt
/temp

View File

@@ -1,4 +1,15 @@
## Core Java IO
### Relevant Articles:
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory)
- [How to Read a Large File Efficiently with Java](https://www.baeldung.com/java-read-lines-large-file)
- [Java Write to File](https://www.baeldung.com/java-write-to-file)
- [FileNotFoundException in Java](https://www.baeldung.com/java-filenotfound-exception)
- [Delete the Contents of a File in Java](https://www.baeldung.com/java-delete-file-contents)
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
- [Java Append Data to a File](https://www.baeldung.com/java-append-to-file)
- [How to Copy a File with Java](https://www.baeldung.com/java-copy-file)
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [[<-- Prev]](/core-java-modules/core-java-io)

View File

@@ -16,57 +16,16 @@
<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>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- utils -->
<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>
@@ -78,12 +37,6 @@
<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>
@@ -91,86 +44,6 @@
<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>
@@ -182,22 +55,6 @@
</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>
@@ -210,70 +67,9 @@
</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>

View File

@@ -0,0 +1,64 @@
package com.baeldung.listfiles;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListFiles {
public static final int DEPTH = 1;
public Set<String> listFilesUsingJavaIO(String dir) {
return Stream.of(new File(dir).listFiles())
.filter(file -> !file.isDirectory())
.map(File::getName)
.collect(Collectors.toSet());
}
public Set<String> listFilesUsingFileWalk(String dir, int depth) throws IOException {
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
return stream.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
}
}
public Set<String> listFilesUsingFileWalkAndVisitor(String dir) throws IOException {
Set<String> fileList = new HashSet<>();
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
fileList.add(file.getFileName()
.toString());
}
return FileVisitResult.CONTINUE;
}
});
return fileList;
}
public Set<String> listFilesUsingDirectoryStream(String dir) throws IOException {
Set<String> fileList = new HashSet<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir))) {
for (Path path : stream) {
if (!Files.isDirectory(path)) {
fileList.add(path.getFileName()
.toString());
}
}
}
return fileList;
}
}

View File

@@ -1,96 +0,0 @@
package com.baeldung.scanner;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Scanner;
@Log4j
public class HasNextVsHasNextLineDemo {
private static final String LINE = "----------------------------";
private static final String END_LINE = "--------OUTPUT--END---------\n";
private static final String INPUT = new StringBuilder()
.append("magic\tproject\n")
.append(" database: oracle\n")
.append("dependencies:\n")
.append("spring:foo:bar\n")
.append("\n").toString();
private static void hasNextBasic() {
printHeader("hasNext() Basic");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
log.info(scanner.next());
}
log.info(END_LINE);
scanner.close();
}
private static void hasNextWithDelimiter() {
printHeader("hasNext() with delimiter");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
String token = scanner.next();
if ("dependencies:".equals(token)) {
scanner.useDelimiter(":");
}
log.info(token);
}
log.info(END_LINE);
scanner.close();
}
private static void hasNextWithDelimiterFixed() {
printHeader("hasNext() with delimiter FIX");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
String token = scanner.next();
if ("dependencies:".equals(token)) {
scanner.useDelimiter(":|\\s+");
}
log.info(token);
}
log.info(END_LINE);
scanner.close();
}
private static void addLineNumber() {
printHeader("add line number by hasNextLine() ");
Scanner scanner = new Scanner(INPUT);
int i = 0;
while (scanner.hasNextLine()) {
log.info(String.format("%d|%s", ++i, scanner.nextLine()));
}
log.info(END_LINE);
scanner.close();
}
private static void printHeader(String title) {
log.info(LINE);
log.info(title);
log.info(LINE);
}
public static void main(String[] args) throws IOException {
setLogger();
hasNextBasic();
hasNextWithDelimiter();
hasNextWithDelimiterFixed();
addLineNumber();
}
//overwrite the logger config
private static void setLogger() throws IOException {
InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
Properties props = new Properties();
props.load(is);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}
}

View File

@@ -1,4 +0,0 @@
log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[DEMO]%m%n

View File

@@ -0,0 +1,80 @@
package com.baeldung.appendtofile;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import com.google.common.base.Charsets;
import com.google.common.io.CharSink;
import com.google.common.io.FileWriteMode;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AppendToFileManualTest {
public static final String fileName = "src/main/resources/countries.properties";
@Before
@After
public void setup() throws Exception {
PrintWriter writer = new PrintWriter(fileName);
writer.print("UK\r\n" + "US\r\n" + "Germany\r\n");
writer.close();
}
@Test
public void whenAppendToFileUsingGuava_thenCorrect() throws IOException {
File file = new File(fileName);
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
chs.write("Spain\r\n");
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException {
File file = new File(fileName);
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception {
FileOutputStream fos = new FileOutputStream(fileName, true);
fos.write("Spain\r\n".getBytes());
fos.close();
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException {
FileWriter fw = new FileWriter(fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Spain");
bw.newLine();
bw.close();
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.appendtofile;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class StreamUtils {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.copyfiles;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class FileCopierIntegrationTest {
File original = new File("src/test/resources/original.txt");
@Before
public void init() throws IOException {
if (!original.exists())
Files.createFile(original.toPath());
}
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
}
@Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
}

View File

@@ -5,15 +5,27 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import org.junit.BeforeClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CreateFilesUnitTest {
@BeforeClass
public static void clean() {
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File file1 = new File(tempDirectory.getAbsolutePath() + "/testFile.txt");
File file2 = new File(tempDirectory, "newFile.txt");
File file3 = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile2.txt");
file1.delete();
file2.delete();
file3.delete();
}
@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");
File fileWithAbsolutePath = new File(tempDirectory.getAbsolutePath() + "/testFile.txt");
assertFalse(fileWithAbsolutePath.exists());
@@ -25,7 +37,7 @@ public class CreateFilesUnitTest {
@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");
File fileWithRelativePath = new File(tempDirectory, "newFile.txt");
assertFalse(fileWithRelativePath.exists());
@@ -37,7 +49,7 @@ public class CreateFilesUnitTest {
@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");
File newFile = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile2.txt");
assertFalse(newFile.exists());

View File

@@ -0,0 +1,94 @@
package com.baeldung.deletecontents;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class FilesClearDataUnitTest {
public static final String FILE_PATH = "src/test/resources/fileexample.txt";
@Before
@After
public void setup() throws IOException {
PrintWriter writer = new PrintWriter(FILE_PATH);
writer.print("This example shows how we can delete the file contents without deleting the file");
writer.close();
}
@Test
public void givenExistingFile_whenDeleteContentUsingPrintWritter_thenEmptyFile() throws IOException {
PrintWriter writer = new PrintWriter(FILE_PATH);
writer.print("");
writer.close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingPrintWritterWithougObject_thenEmptyFile() throws IOException {
new PrintWriter(FILE_PATH).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingFileWriter_thenEmptyFile() throws IOException {
new FileWriter(FILE_PATH, false).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingFileOutputStream_thenEmptyFile() throws IOException {
new FileOutputStream(FILE_PATH).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingFileUtils_thenEmptyFile() throws IOException {
FileUtils.write(new File(FILE_PATH), "", Charset.defaultCharset());
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingNIOFiles_thenEmptyFile() throws IOException {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(FILE_PATH));
writer.write("");
writer.flush();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingNIOFileChannel_thenEmptyFile() throws IOException {
FileChannel.open(Paths.get(FILE_PATH), StandardOpenOption.WRITE).truncate(0).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingGuava_thenEmptyFile() throws IOException {
File file = new File(FILE_PATH);
byte[] empty = new byte[0];
com.google.common.io.Files.write(empty, file);
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.deletecontents;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class StreamUtils {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
}

View File

@@ -0,0 +1,100 @@
package com.baeldung.directories;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NewDirectoryUnitTest {
private static final File TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir"));
@Before
public void beforeEach() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedInNewDirectory = new File(newDirectory, "nested_directory");
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
File nestedInExistingDirectory = new File(existingDirectory, "nested_directory");
nestedInNewDirectory.delete();
newDirectory.delete();
nestedInExistingDirectory.delete();
existingDirectory.mkdir();
existingNestedDirectory.mkdir();
}
@Test
public void givenUnexistingDirectory_whenMkdir_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
assertFalse(newDirectory.exists());
boolean directoryCreated = newDirectory.mkdir();
assertTrue(directoryCreated);
}
@Test
public void givenExistingDirectory_whenMkdir_thenFalse() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
newDirectory.mkdir();
assertTrue(newDirectory.exists());
boolean directoryCreated = newDirectory.mkdir();
assertFalse(directoryCreated);
}
@Test
public void givenUnexistingNestedDirectories_whenMkdir_thenFalse() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedDirectory = new File(newDirectory, "nested_directory");
assertFalse(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdir();
assertFalse(directoriesCreated);
}
@Test
public void givenUnexistingNestedDirectories_whenMkdirs_thenTrue() {
File newDirectory = new File(System.getProperty("java.io.tmpdir") + File.separator + "new_directory");
File nestedDirectory = new File(newDirectory, "nested_directory");
assertFalse(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdirs();
assertTrue(directoriesCreated);
}
@Test
public void givenExistingParentDirectories_whenMkdirs_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "existing_directory");
newDirectory.mkdir();
File nestedDirectory = new File(newDirectory, "nested_directory");
assertTrue(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdirs();
assertTrue(directoriesCreated);
}
@Test
public void givenExistingNestedDirectories_whenMkdirs_thenFalse() {
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
assertTrue(existingDirectory.exists());
assertTrue(existingNestedDirectory.exists());
boolean directoriesCreated = existingNestedDirectory.mkdirs();
assertFalse(directoriesCreated);
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.filenotfoundexception;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class FileNotFoundExceptionUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FileNotFoundExceptionUnitTest.class);
private String fileName = Double.toString(Math.random());
@Test(expected = BusinessException.class)
public void raiseBusinessSpecificException() throws IOException {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
throw new BusinessException("BusinessException: necessary file was not present.");
}
}
@Test
public void createFile() throws IOException {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
try {
new File(fileName).createNewFile();
readFailingFile();
} catch (IOException ioe) {
throw new RuntimeException("BusinessException: even creation is not possible.");
}
}
}
@Test
public void logError() throws IOException {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
LOG.error("Optional file " + fileName + " was not found.");
}
}
private void readFailingFile() throws IOException {
BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
rd.readLine();
// no need to close file
}
private class BusinessException extends RuntimeException {
BusinessException(String string) {
super(string);
}
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.listfiles;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import com.baeldung.listfiles.ListFiles;
public class ListFilesUnitTest {
private ListFiles listFiles = new ListFiles();
private String DIRECTORY = "src/test/resources/listFilesUnitTestFolder";
private static final int DEPTH = 1;
private Set<String> EXPECTED_FILE_LIST = new HashSet<String>() {
{
add("test.xml");
add("employee.json");
add("students.json");
add("country.txt");
}
};
@Test
public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY));
}
@Test
public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));
}
@Test
public void givenDir_whenWalkingTreeWithVisitor_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalkAndVisitor(DIRECTORY));
}
@Test
public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingDirectoryStream(DIRECTORY));
}
}

View File

@@ -0,0 +1,107 @@
package com.baeldung.readlargefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
@Ignore("need large file for testing")
public class ReadLargeFileUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
// tests - iterate lines in a file
@Test
public final void givenUsingGuava_whenIteratingAFile_thenCorrect() throws IOException {
final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
// final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
logMemory();
Files.readLines(new File(path), Charsets.UTF_8);
logMemory();
}
@Test
public final void givenUsingCommonsIo_whenIteratingAFileInMemory_thenCorrect() throws IOException {
// final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
logMemory();
FileUtils.readLines(new File(path));
logMemory();
}
@Test
public final void whenStreamingThroughAFile_thenCorrect() throws IOException {
final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
// final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
logMemory();
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
final String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
logMemory();
}
@Test
public final void givenUsingApacheIo_whenStreamingThroughAFile_thenCorrect() throws IOException {
final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
// final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
logMemory();
final LineIterator it = FileUtils.lineIterator(new File(path), "UTF-8");
try {
while (it.hasNext()) {
final String line = it.nextLine();
// do something with line
}
} finally {
LineIterator.closeQuietly(it);
}
logMemory();
}
// utils
private final void logMemory() {
logger.info("Max Memory: {} Mb", Runtime.getRuntime()
.maxMemory() / 1048576);
logger.info("Total Memory: {} Mb", Runtime.getRuntime()
.totalMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime()
.freeMemory() / 1048576);
}
}

View File

@@ -1,44 +0,0 @@
package com.baeldung.scanner;
import static org.junit.Assert.assertEquals;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.junit.Test;
public class JavaScannerUnitTest {
@Test
public void whenReadingLines_thenCorrect() {
String input = "Scanner\nTest\n";
try (Scanner scanner = new Scanner(input)) {
assertEquals("Scanner", scanner.nextLine());
assertEquals("Test", scanner.nextLine());
}
}
@Test
public void whenReadingPartialLines_thenCorrect() {
String input = "Scanner\n";
try (Scanner scanner = new Scanner(input)) {
scanner.useDelimiter("");
scanner.next();
assertEquals("canner", scanner.nextLine());
}
}
@Test(expected = NoSuchElementException.class)
public void givenNoNewLine_whenReadingNextLine_thenThrowNoSuchElementException() {
try (Scanner scanner = new Scanner("")) {
String result = scanner.nextLine();
}
}
@Test(expected = IllegalStateException.class)
public void givenScannerIsClosed_whenReadingNextLine_thenThrowIllegalStateException() {
Scanner scanner = new Scanner("");
scanner.close();
String result = scanner.nextLine();
}
}

View File

@@ -0,0 +1,186 @@
package com.baeldung.writetofile;
import static org.junit.Assert.assertEquals;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
public class JavaWriteToFileUnitTest {
private String fileName = "src/test/resources/test_write.txt";
private String fileName1 = "src/test/resources/test_write_1.txt";
private String fileName2 = "src/test/resources/test_write_2.txt";
private String fileName3 = "src/test/resources/test_write_3.txt";
private String fileName4 = "src/test/resources/test_write_4.txt";
private String fileName5 = "src/test/resources/test_write_5.txt";
@Test
public void whenWriteStringUsingBufferedWritter_thenCorrect() throws IOException {
final String str = "Hello";
final BufferedWriter writer = new BufferedWriter(new FileWriter(fileName3));
writer.write(str);
writer.close();
}
@Test
public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() throws IOException {
final String str = "World";
final BufferedWriter writer = new BufferedWriter(new FileWriter(fileName3, true));
writer.append(' ');
writer.append(str);
writer.close();
}
@Test
public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() throws IOException {
final FileWriter fileWriter = new FileWriter(fileName);
final PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
@Test
public void givenWritingStringToFile_whenUsingFileOutputStream_thenCorrect() throws IOException {
final String str = "Hello";
final FileOutputStream outputStream = new FileOutputStream(fileName3);
final byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
//
@Test
public void givenWritingToFile_whenUsingDataOutputStream_thenCorrect() throws IOException {
final String value = "Hello";
final FileOutputStream fos = new FileOutputStream(fileName1);
final DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(value);
outStream.close();
String result;
final FileInputStream fis = new FileInputStream(fileName1);
final DataInputStream reader = new DataInputStream(fis);
result = reader.readUTF();
reader.close();
assertEquals(value, result);
}
@Test
public void whenWritingToSpecificPositionInFile_thenCorrect() throws IOException {
final int data1 = 2014;
final int data2 = 1500;
writeToPosition(fileName2, data1, 4);
assertEquals(data1, readFromPosition(fileName2, 4));
writeToPosition(fileName2, data2, 4);
assertEquals(data2, readFromPosition(fileName2, 4));
}
@Test
public void whenTryToLockFile_thenItShouldBeLocked() throws IOException {
final RandomAccessFile stream = new RandomAccessFile(fileName4, "rw");
final FileChannel channel = stream.getChannel();
FileLock lock = null;
try {
lock = channel.tryLock();
} catch (final OverlappingFileLockException e) {
stream.close();
channel.close();
}
stream.writeChars("test lock");
lock.release();
stream.close();
channel.close();
}
@Test
public void givenWritingToFile_whenUsingFileChannel_thenCorrect() throws IOException {
final RandomAccessFile stream = new RandomAccessFile(fileName5, "rw");
final FileChannel channel = stream.getChannel();
final String value = "Hello";
final byte[] strBytes = value.getBytes();
final ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
final RandomAccessFile reader = new RandomAccessFile(fileName5, "r");
assertEquals(value, reader.readLine());
reader.close();
}
@Test
public void whenWriteToTmpFile_thenCorrect() throws IOException {
final String toWrite = "Hello";
final File tmpFile = File.createTempFile("test", ".tmp");
final FileWriter writer = new FileWriter(tmpFile);
writer.write(toWrite);
writer.close();
final BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
assertEquals(toWrite, reader.readLine());
reader.close();
}
@Test
public void givenUsingJava7_whenWritingToFile_thenCorrect() throws IOException {
final String str = "Hello";
final Path path = Paths.get(fileName3);
final byte[] strToBytes = str.getBytes();
Files.write(path, strToBytes);
final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0);
assertEquals(str, read);
}
// UTIL
// use RandomAccessFile to write data at specific position in the file
private void writeToPosition(final String filename, final int data, final long position) throws IOException {
final RandomAccessFile writer = new RandomAccessFile(filename, "rw");
writer.seek(position);
writer.writeInt(data);
writer.close();
}
// use RandomAccessFile to read data from specific position in the file
private int readFromPosition(final String filename, final long position) throws IOException {
int result = 0;
final RandomAccessFile reader = new RandomAccessFile(filename, "r");
reader.seek(position);
result = reader.readInt();
reader.close();
return result;
}
}

View File

@@ -0,0 +1,3 @@
UK
US
Germany

View File

@@ -0,0 +1 @@
This example shows how we can delete the file contents without deleting the file

View File

@@ -0,0 +1 @@
This is a sample txt file for unit test ListFilesUnitTest

View File

@@ -0,0 +1 @@
Some StringProduct name is iPhone and its price is 1000 $

View File

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

View File

@@ -0,0 +1 @@
Hello