[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

@@ -4,30 +4,20 @@ This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [How to Read a Large File Efficiently with Java](http://www.baeldung.com/java-read-lines-large-file)
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
- [Java Write to File](http://www.baeldung.com/java-write-to-file)
- [Java Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
- [Java Scanner](http://www.baeldung.com/java-scanner)
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
- [Java Directory Size](http://www.baeldung.com/java-folder-size)
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
- [File Size in Java](http://www.baeldung.com/java-file-size)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [How to Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Java Append Data to a File](http://www.baeldung.com/java-append-to-file)
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)
- [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
- [Getting a Files Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
- [How to Avoid the Java FileNotFoundException When Loading Resources](https://www.baeldung.com/java-classpath-resource-cannot-be-opened)
- [[More -->]](/core-java-modules/core-java-io-2)

View File

@@ -1,84 +0,0 @@
package com.baeldung.bufferedreader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.stream.Collectors;
public class BufferedReaderExample {
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public String readAllLinesWithStream(BufferedReader reader) {
return reader
.lines()
.collect(Collectors.joining(System.lineSeparator()));
}
public String readAllCharsOneByOne(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
int value;
while ((value = reader.read()) != -1) {
content.append((char) value);
}
return content.toString();
}
public String readMultipleChars(BufferedReader reader) throws IOException {
int length = 5;
char[] chars = new char[length];
int charsRead = reader.read(chars, 0, length);
String result;
if (charsRead != -1) {
result = new String(chars, 0, charsRead);
} else {
result = "";
}
return result;
}
public String readFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("src/main/resources/input.txt"));
String content = readAllLines(reader);
return content;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String readFileTryWithResources() {
try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) {
String content = readAllLines(reader);
return content;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -1,42 +0,0 @@
package com.baeldung.dirmonitoring;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
private static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
LOG.debug("File: " + file.getName() + " created");
}
@Override
public void onFileDelete(File file) {
LOG.debug("File: " + file.getName() + " deleted");
}
@Override
public void onFileChange(File file) {
LOG.debug("File: " + file.getName() + " changed");
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}

View File

@@ -1,48 +0,0 @@
package com.baeldung.stream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class OutputStreamExamples {
public void fileOutputStreamByteSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes);
}
}
public void fileOutputStreamByteSubSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes, 6, 5);
}
}
public void fileOutputStreamByteSingle(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes[6]);
}
}
public void bufferedOutputStream(String file, String... data) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
for (String s : data) {
out.write(s.getBytes());
out.write(" ".getBytes());
}
}
}
public void outputStreamWriter(String file, String data) throws IOException {
try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) {
writer.write(data);
}
}
}

View File

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

@@ -1,58 +0,0 @@
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.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
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

@@ -1,48 +0,0 @@
package com.baeldung.file;
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;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
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

@@ -1,76 +0,0 @@
package com.baeldung.stream;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
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

@@ -1,56 +0,0 @@
package org.baeldung.java.io;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import static java.nio.channels.Channels.newChannel;
import static org.junit.Assert.assertEquals;
public class InputStreamToByteBufferUnitTest {
@Test
public void givenUsingCoreClasses_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
byte[] input = new byte[] { 0, 1, 2 };
InputStream initialStream = new ByteArrayInputStream(input);
ByteBuffer byteBuffer = ByteBuffer.allocate(3);
while (initialStream.available() > 0) {
byteBuffer.put((byte) initialStream.read());
}
assertEquals(byteBuffer.position(), input.length);
}
@Test
public void givenUsingGuava__whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
InputStream initialStream = ByteSource
.wrap(new byte[] { 0, 1, 2 })
.openStream();
byte[] targetArray = ByteStreams.toByteArray(initialStream);
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
while (bufferByte.hasRemaining()) {
bufferByte.get();
}
assertEquals(bufferByte.position(), targetArray.length);
}
@Test
public void givenUsingCommonsIo_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
byte[] input = new byte[] { 0, 1, 2 };
InputStream initialStream = new ByteArrayInputStream(input);
ByteBuffer byteBuffer = ByteBuffer.allocate(3);
ReadableByteChannel channel = newChannel(initialStream);
IOUtils.readFully(channel, byteBuffer);
assertEquals(byteBuffer.position(), input.length);
}
}

View File

@@ -1,99 +0,0 @@
package org.baeldung.java.io;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
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

@@ -1,140 +0,0 @@
package org.baeldung.java.io;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
public class JavaFileUnitTest {
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
@BeforeClass
public static void setup() throws IOException {
Files.createDirectory(Paths.get(TEMP_DIR));
}
@AfterClass
public static void cleanup() throws IOException {
FileUtils.deleteDirectory(new File(TEMP_DIR));
}
@Test
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
final boolean success = newFile.createNewFile();
assertTrue(success);
}
@Test
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
Files.createFile(newFilePath);
}
@Test
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
}
@Test
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
}
// move a file
@Test
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
fileToMove.createNewFile();// .exists();
final File destDir = new File(TEMP_DIR + "/");
destDir.mkdir();
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
if (!isMoved) {
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
}
}
@Test
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
final Path targetPath = Paths.get(TEMP_DIR + "/");
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
}
@Test
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
fileToMove.createNewFile();
final File destDir = new File(TEMP_DIR + "/temp");
final File targetFile = new File(destDir, fileToMove.getName());
com.google.common.io.Files.createParentDirs(targetFile);
com.google.common.io.Files.move(fileToMove, targetFile);
}
@Test
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
}
@Test
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
}
// delete a file
@Test
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
final boolean success = fileToDelete.delete();
assertTrue(success);
}
@Test
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
}
@Test
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
final boolean success = FileUtils.deleteQuietly(fileToDelete);
assertTrue(success);
}
@Test
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
}
}

View File

@@ -1,248 +0,0 @@
package org.baeldung.java.io;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@SuppressWarnings("unused")
public class JavaInputStreamToXUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private static final int DEFAULT_SIZE = 1500000;
// tests - InputStream to String
@Test
public final void givenUsingJava5_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
assertEquals(textBuilder.toString(), originalString);
}
@Test
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); // exampleString.getBytes(StandardCharsets.UTF_8);
// When
String text;
try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
text = scanner.useDelimiter("\\A").next();
}
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final ByteSource byteSource = new ByteSource() {
@Override
public final InputStream openStream() throws IOException {
return inputStream;
}
};
final String text = byteSource.asCharSource(Charsets.UTF_8).read();
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingGuavaAndJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
// When
String text;
try (final Reader reader = new InputStreamReader(inputStream)) {
text = CharStreams.toString(reader);
}
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingCommonsIo_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
// When
final String text = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingCommonsIoWithCopy_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
// When
final StringWriter writer = new StringWriter();
final String encoding = StandardCharsets.UTF_8.name();
IOUtils.copy(inputStream, writer, encoding);
assertThat(writer.toString(), equalTo(originalString));
}
@Test
public final void givenUsingTempFile_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
// When
Path tempFile = java.nio.file.Files.createTempDirectory("").resolve(UUID.randomUUID().toString() + ".tmp");
java.nio.file.Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
String result = new String(java.nio.file.Files.readAllBytes(tempFile));
assertThat(result, equalTo(originalString));
}
// tests - InputStream to byte[]
@Test
public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = new byte[initialStream.available()];
initialStream.read(targetArray);
}
@Test
public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
final byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
final byte[] byteArray = buffer.toByteArray();
}
@Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 }).openStream();
final byte[] targetArray = ByteStreams.toByteArray(initialStream);
}
@Test
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = IOUtils.toByteArray(initialStream);
}
// tests - InputStream to File
@Test
public final void whenConvertingToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
IOUtils.closeQuietly(initialStream);
IOUtils.closeQuietly(outStream);
}
@Test
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
final byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = initialStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
IOUtils.closeQuietly(initialStream);
IOUtils.closeQuietly(outStream);
}
@Test
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final File targetFile = new File("src/test/resources/targetFile.tmp");
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(initialStream);
}
@Test
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
final File targetFile = new File("src/test/resources/targetFile.tmp");
Files.write(buffer, targetFile);
IOUtils.closeQuietly(initialStream);
}
@Test
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
final InputStream initialStream = FileUtils.openInputStream(new File("src/test/resources/sample.txt"));
final File targetFile = new File("src/test/resources/targetFile.tmp");
FileUtils.copyInputStreamToFile(initialStream, targetFile);
}
@Test
public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException {
String originalString = randomAlphabetic(8);
InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] byteArray = buffer.toByteArray();
String text = new String(byteArray, StandardCharsets.UTF_8);
assertThat(text, equalTo(originalString));
}
}

View File

@@ -1,186 +0,0 @@
package org.baeldung.java.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Scanner;
import org.junit.Test;
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

@@ -1,117 +0,0 @@
package org.baeldung.java.io;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
public class JavaXToInputStreamUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
// tests - String - InputStream
@Test
public final void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect() throws IOException {
final String initialString = "text";
final InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
IOUtils.closeQuietly(targetStream);
}
@Test
public final void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() throws IOException {
final String initialString = "text";
final InputStream targetStream = new ReaderInputStream(CharSource.wrap(initialString).openStream());
IOUtils.closeQuietly(targetStream);
}
@Test
public final void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect() throws IOException {
final String initialString = "text";
final InputStream targetStream = IOUtils.toInputStream(initialString);
IOUtils.closeQuietly(targetStream);
}
// byte array - InputStream
@Test
public final void givenUsingPlainJava_whenConvertingByteArrayToInputStream_thenCorrect() throws IOException {
final byte[] initialArray = { 0, 1, 2 };
final InputStream targetStream = new ByteArrayInputStream(initialArray);
IOUtils.closeQuietly(targetStream);
}
@Test
public final void givenUsingGuava_whenConvertingByteArrayToInputStream_thenCorrect() throws IOException {
final byte[] initialArray = { 0, 1, 2 };
final InputStream targetStream = ByteSource.wrap(initialArray).openStream();
IOUtils.closeQuietly(targetStream);
}
// File - InputStream
@Test
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = new FileInputStream(initialFile);
IOUtils.closeQuietly(targetStream);
}
@Test
public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile));
IOUtils.closeQuietly(targetStream);
}
@Test
public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
final File anotherFile = new File("src/test/resources/anothersample.txt");
final InputStream targetStream = new FileInputStream(initialFile);
final InputStream anotherTargetStream = new FileInputStream(anotherFile);
InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream);
IOUtils.closeQuietly(targetStream);
IOUtils.closeQuietly(anotherTargetStream);
IOUtils.closeQuietly(sequenceTargetStream);
}
@Test
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = Files.asByteSource(initialFile).openStream();
IOUtils.closeQuietly(targetStream);
}
@Test
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = FileUtils.openInputStream(initialFile);
IOUtils.closeQuietly(targetStream);
}
}

View File

@@ -1,61 +0,0 @@
package org.baeldung.java.io;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.commons.io.output.StringBuilderWriter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.CharSink;
public class JavaXToWriterUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
// tests - byte[] to Writer
@Test
public void givenPlainJava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
final byte[] initialArray = "With Java".getBytes();
final Writer targetWriter = new StringWriter().append(new String(initialArray));
targetWriter.close();
assertEquals("With Java", targetWriter.toString());
}
@Test
public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
final byte[] initialArray = "With Guava".getBytes();
final String buffer = new String(initialArray);
final StringWriter stringWriter = new StringWriter();
final CharSink charSink = new CharSink() {
@Override
public final Writer openStream() throws IOException {
return stringWriter;
}
};
charSink.write(buffer);
stringWriter.close();
assertEquals("With Guava", stringWriter.toString());
}
@Test
public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
final byte[] initialArray = "With Commons IO".getBytes();
final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray)));
targetWriter.close();
assertEquals("With Commons IO", targetWriter.toString());
}
}

View File

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

View File

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