[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.bufferedreader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BufferedReaderExampleUnitTest {
|
||||
|
||||
private static final String FILE_PATH = "src/main/resources/input.txt";
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readAllLines(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadAllLinesWithStream_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readAllLinesWithStream(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFile_thenReturnsContent() {
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readFile();
|
||||
|
||||
assertThat(content.toString()).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadAllCharsOneByOne_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readAllCharsOneByOne(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadMultipleChars_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readMultipleChars(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).isEqualTo("Lorem");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFileTryWithResources_thenReturnsContent() {
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readFileTryWithResources();
|
||||
|
||||
assertThat(content.toString()).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.csv;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.opencsv.CSVReader;
|
||||
|
||||
public class ReadCSVInArrayUnitTest {
|
||||
public static final String COMMA_DELIMITER = ",";
|
||||
public static final String CSV_FILE = "src/test/resources/book.csv";
|
||||
public static final List<List<String>> EXPECTED_ARRAY = Collections.unmodifiableList(new ArrayList<List<String>>() {
|
||||
{
|
||||
add(new ArrayList<String>() {
|
||||
{
|
||||
add("Mary Kom");
|
||||
add("Unbreakable");
|
||||
}
|
||||
});
|
||||
add(new ArrayList<String>() {
|
||||
{
|
||||
add("Kapil Isapuari");
|
||||
add("Farishta");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenBufferedReader_thenContentsAsExpected() throws IOException {
|
||||
List<List<String>> records = new ArrayList<List<String>>();
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(CSV_FILE))) {
|
||||
String line = "";
|
||||
while ((line = br.readLine()) != null) {
|
||||
String[] values = line.split(COMMA_DELIMITER);
|
||||
records.add(Arrays.asList(values));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
|
||||
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
|
||||
.toArray(),
|
||||
records.get(i)
|
||||
.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenScanner_thenContentsAsExpected() throws IOException {
|
||||
List<List<String>> records = new ArrayList<List<String>>();
|
||||
try (Scanner scanner = new Scanner(new File(CSV_FILE));) {
|
||||
while (scanner.hasNextLine()) {
|
||||
records.add(getRecordFromLine(scanner.nextLine()));
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
|
||||
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
|
||||
.toArray(),
|
||||
records.get(i)
|
||||
.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> getRecordFromLine(String line) {
|
||||
List<String> values = new ArrayList<String>();
|
||||
try (Scanner rowScanner = new Scanner(line)) {
|
||||
rowScanner.useDelimiter(COMMA_DELIMITER);
|
||||
while (rowScanner.hasNext()) {
|
||||
values.add(rowScanner.next());
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenOpencsv_thenContentsAsExpected() throws IOException {
|
||||
List<List<String>> records = new ArrayList<List<String>>();
|
||||
try (CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));) {
|
||||
String[] values = null;
|
||||
while ((values = csvReader.readNext()) != null) {
|
||||
records.add(Arrays.asList(values));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
|
||||
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
|
||||
.toArray(),
|
||||
records.get(i)
|
||||
.toArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.csv;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class WriteCsvFileExampleUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
|
||||
|
||||
private WriteCsvFileExample csvExample;
|
||||
|
||||
@Before
|
||||
public void setupClass() {
|
||||
csvExample = new WriteCsvFileExample();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommaContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
|
||||
String data = "three,two,one";
|
||||
String escapedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
String expectedData = "\"three,two,one\"";
|
||||
assertEquals(expectedData, escapedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQuoteContainingData_whenEscapeSpecialCharacters_stringReturnedFormatted() {
|
||||
String data = "She said \"Hello\"";
|
||||
String escapedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
String expectedData = "\"She said \"\"Hello\"\"\"";
|
||||
assertEquals(expectedData, escapedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewlineContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
|
||||
String dataNewline = "This contains\na newline";
|
||||
String dataCarriageReturn = "This contains\r\na newline and carriage return";
|
||||
String escapedDataNl = csvExample.escapeSpecialCharacters(dataNewline);
|
||||
String escapedDataCr = csvExample.escapeSpecialCharacters(dataCarriageReturn);
|
||||
|
||||
String expectedData = "This contains a newline";
|
||||
assertEquals(expectedData, escapedDataNl);
|
||||
String expectedDataCr = "This contains a newline and carriage return";
|
||||
assertEquals(expectedDataCr, escapedDataCr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSpecialData_whenEscapeSpecialCharacters_stringReturnedUnchanged() {
|
||||
String data = "This is nothing special";
|
||||
String returnedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
assertEquals(data, returnedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() throws IOException {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
||||
File csvOutputFile = File.createTempFile("exampleOutput", ".csv");
|
||||
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
|
||||
dataLines.stream()
|
||||
.map(csvExample::convertToCSV)
|
||||
.forEach(pw::println);
|
||||
} catch (FileNotFoundException e) {
|
||||
LOG.error("IOException " + e.getMessage());
|
||||
}
|
||||
|
||||
assertTrue(csvOutputFile.exists());
|
||||
csvOutputFile.deleteOnExit();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.download;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileDownloadIntegrationTest {
|
||||
|
||||
static String FILE_URL = "http://ovh.net/files/1Mio.dat";
|
||||
static String FILE_NAME = "file.dat";
|
||||
static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116";
|
||||
|
||||
@Test
|
||||
public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
|
||||
|
||||
FileDownload.downloadWithJavaIO(FILE_URL, FILE_NAME);
|
||||
assertTrue(checkMd5Hash(FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaNIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
|
||||
|
||||
FileDownload.downloadWithJavaNIO(FILE_URL, FILE_NAME);
|
||||
assertTrue(checkMd5Hash(FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJava7IO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
|
||||
|
||||
FileDownload.downloadWithJava7IO(FILE_URL, FILE_NAME);
|
||||
assertTrue(checkMd5Hash(FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAHCLibrary_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException, ExecutionException, InterruptedException {
|
||||
|
||||
FileDownload.downloadWithAHC(FILE_URL, FILE_NAME);
|
||||
assertTrue(checkMd5Hash(FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenApacheCommonsIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
|
||||
|
||||
FileDownload.downloadWithApacheCommons(FILE_URL, FILE_NAME);
|
||||
assertTrue(checkMd5Hash(FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaIO_whenDownloadingFileStops_thenDownloadShouldBeResumedCorrectly() throws NoSuchAlgorithmException, IOException, URISyntaxException {
|
||||
|
||||
ResumableDownload.downloadFileWithResume(FILE_URL, FILE_NAME);
|
||||
assertTrue(checkMd5Hash(FILE_NAME));
|
||||
}
|
||||
|
||||
private boolean checkMd5Hash(String filename) throws IOException, NoSuchAlgorithmException {
|
||||
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
md.update(Files.readAllBytes(Paths.get(filename)));
|
||||
byte[] digest = md.digest();
|
||||
String myChecksum = DatatypeConverter.printHexBinary(digest);
|
||||
|
||||
return myChecksum.equalsIgnoreCase(FILE_MD5_HASH);
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
if (Files.exists(Paths.get(FILE_NAME))) {
|
||||
Files.delete(Paths.get(FILE_NAME));
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() throws IOException {
|
||||
if (Files.exists(Paths.get(FILE_NAME))) {
|
||||
Files.delete(Paths.get(FILE_NAME));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.extension;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class ExtensionUnitTest {
|
||||
private Extension extension = new Extension();
|
||||
|
||||
@Test
|
||||
public void getExtension_whenApacheCommonIO_thenExtensionIsTrue() {
|
||||
String expectedExtension = "txt";
|
||||
String actualExtension = extension.getExtensionByApacheCommonLib("jarvis.txt");
|
||||
Assert.assertEquals(expectedExtension, actualExtension);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getExtension_whenStringHandle_thenExtensionIsTrue() {
|
||||
String expectedExtension = "java";
|
||||
Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
|
||||
Assert.assertEquals(expectedExtension, actualExtension.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getExtension_whenGuava_thenExtensionIsTrue() {
|
||||
String expectedExtension = "class";
|
||||
String actualExtension = extension.getExtensionByGuava("baeldung/Demo.class");
|
||||
Assert.assertEquals(expectedExtension, actualExtension);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class FileOperationsManualTest {
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
InputStream inputStream = new FileInputStream(file);
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Class clazz = FileOperationsManualTest.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||
String expectedData = "MIT License";
|
||||
|
||||
Class clazz = Matchers.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Example Domain";
|
||||
|
||||
URL urlObject = new URL("http://www.example.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
byte[] fileBytes = Files.readAllBytes(path);
|
||||
String data = new String(fileBytes);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
Stream<String> lines = Files.lines(path);
|
||||
String data = lines.collect(Collectors.joining("\n"));
|
||||
lines.close();
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
resultStringBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException {
|
||||
String expectedData = "This is a content of the file";
|
||||
|
||||
FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt");
|
||||
String data = IOUtils.toString(fis, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
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;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
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;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class FilesManualTest {
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
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.files.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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.baeldung.filechannel;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileChannelUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
|
||||
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals("Hello world", fileContent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelUsingFileInputStream_thenCorrect() throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
FileInputStream fin = new FileInputStream("src/test/resources/test_read.in");
|
||||
FileChannel channel = fin.getChannel();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals("Hello world", fileContent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadAFileSectionIntoMemoryWithFileChannel_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
|
||||
|
||||
MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5);
|
||||
|
||||
if (buff.hasRemaining()) {
|
||||
byte[] data = new byte[buff.remaining()];
|
||||
buff.get(data);
|
||||
assertEquals("world", new String(data, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
|
||||
String file = "src/test/resources/test_write_using_filechannel.txt";
|
||||
try (RandomAccessFile writer = new RandomAccessFile(file, "rw");
|
||||
FileChannel channel = writer.getChannel();) {
|
||||
ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
channel.write(buff);
|
||||
|
||||
// now we verify whether the file was written correctly
|
||||
RandomAccessFile reader = new RandomAccessFile(file, "r");
|
||||
assertEquals("Hello world", reader.readLine());
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenWriteAFileUsingLockAFileSectionWithFileChannel_thenCorrect() throws IOException {
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "rw");
|
||||
FileChannel channel = reader.getChannel();
|
||||
FileLock fileLock = channel.tryLock(6, 5, Boolean.FALSE);) {
|
||||
|
||||
assertNotNull(fileLock);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelGetPosition_thenCorrect() throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
|
||||
// the original file is 11 bytes long, so that's where the position pointer should be
|
||||
assertEquals(11, channel.position());
|
||||
|
||||
channel.position(4);
|
||||
assertEquals(4, channel.position());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSize_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();) {
|
||||
|
||||
// the original file is 11 bytes long, so that's where the position pointer should be
|
||||
assertEquals(11, channel.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTruncateFile_thenCorrect() throws IOException {
|
||||
String input = "this is a test input";
|
||||
|
||||
FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt");
|
||||
FileChannel channel = fout.getChannel();
|
||||
|
||||
ByteBuffer buff = ByteBuffer.wrap(input.getBytes());
|
||||
channel.write(buff);
|
||||
buff.flip();
|
||||
|
||||
channel = channel.truncate(5);
|
||||
assertEquals(5, channel.size());
|
||||
|
||||
fout.close();
|
||||
channel.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FilesReadAllLinesUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerIntUnitTest {
|
||||
|
||||
protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
|
||||
List<Integer> numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
|
||||
assertTrue("File does not has 2 lines", numbers.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerStringUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.filesystem.jndi.test;
|
||||
|
||||
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class LookupFSJNDIIntegrationTest {
|
||||
LookupFSJNDI fsjndi;
|
||||
InitialContext ctx = null;
|
||||
final String FILENAME = "test.find";
|
||||
|
||||
public LookupFSJNDIIntegrationTest() {
|
||||
try {
|
||||
fsjndi = new LookupFSJNDI();
|
||||
} catch (NamingException e) {
|
||||
fsjndi = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInitializationLookupFSJNDIIsNotNull_thenSuccess() {
|
||||
assertNotNull("Class LookupFSJNDI has instance", fsjndi);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLookupFSJNDI_whengetInitialContextIsNotNull_thenSuccess() {
|
||||
ctx = fsjndi.getCtx();
|
||||
assertNotNull("Context exists", ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInitialContext_whenLokupFileExists_thenSuccess() {
|
||||
File file = fsjndi.getFile(FILENAME);
|
||||
assertNotNull("File exists", file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.java.mimetype;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.FileNameMap;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import javax.activation.MimetypesFileTypeMap;
|
||||
|
||||
import org.apache.tika.Tika;
|
||||
import org.junit.Test;
|
||||
|
||||
import net.sf.jmimemagic.Magic;
|
||||
import net.sf.jmimemagic.MagicException;
|
||||
import net.sf.jmimemagic.MagicMatch;
|
||||
import net.sf.jmimemagic.MagicMatchNotFoundException;
|
||||
import net.sf.jmimemagic.MagicParseException;
|
||||
|
||||
/**
|
||||
* Test class demonstrating various strategies to resolve MIME type of a file.
|
||||
* @author tritty
|
||||
*
|
||||
*/
|
||||
public class MimeTypeUnitTest {
|
||||
/**
|
||||
* Expected Ouput.
|
||||
*/
|
||||
public static final String PNG_EXT = "image/png";
|
||||
|
||||
/**
|
||||
* The location of the file.
|
||||
*/
|
||||
public static final String FILE_LOC = "src/test/resources/product.png";
|
||||
|
||||
/**
|
||||
* Test method, demonstrating usage in Java 7.
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingJava7_thenSuccess() throws IOException {
|
||||
final Path path = new File(FILE_LOC).toPath();
|
||||
final String mimeType = Files.probeContentType(path);
|
||||
assertEquals(mimeType, PNG_EXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method demonstrating the usage of URLConnection to resolve MIME type.
|
||||
*
|
||||
* @throws MalformedURLException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingGetContentType_thenSuccess() throws MalformedURLException, IOException {
|
||||
final File file = new File(FILE_LOC);
|
||||
final URLConnection connection = file.toURL()
|
||||
.openConnection();
|
||||
final String mimeType = connection.getContentType();
|
||||
assertEquals(mimeType, PNG_EXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method demonstrating the usage of URLConnection to resolve MIME type.
|
||||
*
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingGuessContentTypeFromName_thenSuccess() {
|
||||
final File file = new File(FILE_LOC);
|
||||
final String mimeType = URLConnection.guessContentTypeFromName(file.getName());
|
||||
assertEquals(mimeType, PNG_EXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method demonstrating the usage of FileNameMap from URLConnection
|
||||
* to resolve MIME type of a file.
|
||||
*
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingGetFileNameMap_thenSuccess() {
|
||||
final File file = new File(FILE_LOC);
|
||||
final FileNameMap fileNameMap = URLConnection.getFileNameMap();
|
||||
final String mimeType = fileNameMap.getContentTypeFor(file.getName());
|
||||
assertEquals(mimeType, PNG_EXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of
|
||||
* MIME type.
|
||||
*
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingMimeTypesFileTypeMap_thenSuccess() {
|
||||
final File file = new File(FILE_LOC);
|
||||
final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
|
||||
final String mimeType = fileTypeMap.getContentType(file.getName());
|
||||
assertEquals(mimeType, PNG_EXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method demonstrating usage of jMimeMagic.
|
||||
*
|
||||
* @throws MagicParseException
|
||||
* @throws MagicMatchNotFoundException
|
||||
* @throws MagicException
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingJmimeMagic_thenSuccess() throws MagicParseException, MagicMatchNotFoundException, MagicException {
|
||||
final File file = new File(FILE_LOC);
|
||||
final Magic magic = new Magic();
|
||||
final MagicMatch match = magic.getMagicMatch(file, false);
|
||||
assertEquals(match.getMimeType(), PNG_EXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method demonstrating usage of Apache Tika.
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingTika_thenSuccess() throws IOException {
|
||||
final File file = new File(FILE_LOC);
|
||||
final Tika tika = new Tika();
|
||||
final String mimeType = tika.detect(file);
|
||||
assertEquals(mimeType, PNG_EXT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.java.nio.selector;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NioEchoLiveTest {
|
||||
|
||||
private Process server;
|
||||
private EchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException, InterruptedException {
|
||||
server = EchoServer.start();
|
||||
client = EchoClient.start();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServerClient_whenServerEchosMessage_thenCorrect() {
|
||||
String resp1 = client.sendMessage("hello");
|
||||
String resp2 = client.sendMessage("world");
|
||||
assertEquals("hello", resp1);
|
||||
assertEquals("world", resp2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
server.destroy();
|
||||
EchoClient.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package com.baeldung.java.nio2;
|
||||
|
||||
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.*;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class FileIntegrationTest {
|
||||
private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), 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));
|
||||
}
|
||||
|
||||
// checking file or dir
|
||||
@Test
|
||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt");
|
||||
assertTrue(Files.notExists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isReadable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isWritable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isExecutable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get(TEMP_DIR);
|
||||
Path p2 = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isSameFile(p1, p2));
|
||||
}
|
||||
|
||||
// reading, writing and creating files
|
||||
// creating file
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
assertTrue(Files.exists(p));
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
assertTrue(Files.isDirectory(p));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path subdir = dir.resolve("subdir");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
Files.createDirectories(subdir);
|
||||
assertTrue(Files.exists(dir));
|
||||
assertTrue(Files.exists(subdir));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||
String prefix = "log_";
|
||||
String suffix = ".txt";
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, prefix, suffix);
|
||||
// like log_8821081429012075286.txt
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, null, null);
|
||||
// like 8600179353689423985.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException {
|
||||
Path p = Files.createTempFile(null, null);
|
||||
// like C:\Users\new\AppData\Local\Temp\6100927974988978748.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
// delete file
|
||||
@Test
|
||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
Files.delete(p);
|
||||
assertFalse(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir);
|
||||
assertTrue(Files.exists(dir));
|
||||
Path file = dir.resolve("file.txt");
|
||||
Files.createFile(file);
|
||||
Files.delete(dir);
|
||||
|
||||
assertTrue(Files.exists(dir));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.delete(p);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.deleteIfExists(p);
|
||||
|
||||
}
|
||||
|
||||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertFalse(Files.exists(file2));
|
||||
Files.copy(file1, file2);
|
||||
assertTrue(Files.exists(file2));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
Files.createFile(file2);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertTrue(Files.exists(file2));
|
||||
Files.copy(file1, file2);
|
||||
Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertFalse(Files.exists(file2));
|
||||
Files.move(file1, file2);
|
||||
assertTrue(Files.exists(file2));
|
||||
assertFalse(Files.exists(file1));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
Files.createFile(file2);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertTrue(Files.exists(file2));
|
||||
Files.move(file1, file2);
|
||||
Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||
assertTrue(Files.exists(file2));
|
||||
assertFalse(Files.exists(file1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.baeldung.java.nio2;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PathManualTest {
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
|
||||
// creating a path
|
||||
@Test
|
||||
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
||||
Path p = Paths.get("/articles", "baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
// retrieving path info
|
||||
@Test
|
||||
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("logs", p.getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.getName(0).toString());
|
||||
assertEquals("baeldung", p.getName(1).toString());
|
||||
assertEquals("logs", p.getName(2).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCountsParts_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals(3, p.getNameCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.subpath(0, 1).toString());
|
||||
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
|
||||
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
|
||||
assertEquals("baeldung", p.subpath(1, 2).toString());
|
||||
assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
|
||||
assertEquals("logs", p.subpath(2, 3).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesParent_thenCorrect() {
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("/articles/baeldung");
|
||||
Path p3 = Paths.get("/articles");
|
||||
Path p4 = Paths.get("/");
|
||||
|
||||
assertEquals("\\articles\\baeldung", p1.getParent().toString());
|
||||
assertEquals("\\articles", p2.getParent().toString());
|
||||
assertEquals("\\", p3.getParent().toString());
|
||||
assertEquals(null, p4.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesRoot_thenCorrect() {
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("c:/articles/baeldung/logs");
|
||||
|
||||
assertEquals("\\", p1.getRoot().toString());
|
||||
assertEquals("c:\\", p2.getRoot().toString());
|
||||
}
|
||||
|
||||
// removing redundancies from path
|
||||
@Test
|
||||
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
|
||||
Path p = Paths.get("/home/./baeldung/articles");
|
||||
p = p.normalize();
|
||||
assertEquals("\\home\\baeldung\\articles", p.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRemovesRedundancies_thenCorrect2() {
|
||||
Path p = Paths.get("/home/baeldung/../articles");
|
||||
p = p.normalize();
|
||||
assertEquals("\\home\\articles", p.toString());
|
||||
}
|
||||
|
||||
// converting a path
|
||||
@Test
|
||||
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
URI uri = p.toUri();
|
||||
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME);
|
||||
assertEquals(HOME, p.toRealPath().toString());
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
|
||||
p.toRealPath();
|
||||
}
|
||||
|
||||
// joining paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\java", p.resolve("/java").toString());
|
||||
}
|
||||
|
||||
// creating a path between 2 paths
|
||||
@Test
|
||||
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("articles");
|
||||
Path p2 = Paths.get("authors");
|
||||
assertEquals("..\\authors", p1.relativize(p2).toString());
|
||||
assertEquals("..\\articles", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("/baeldung");
|
||||
Path p2 = Paths.get("/baeldung/authors/articles");
|
||||
assertEquals("authors\\articles", p1.relativize(p2).toString());
|
||||
assertEquals("..\\..", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
// comparing 2 paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
Path p2 = Paths.get("/baeldung/articles");
|
||||
Path p3 = Paths.get("/baeldung/authors");
|
||||
|
||||
assertTrue(p1.equals(p2));
|
||||
assertFalse(p1.equals(p3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsStart_thenCorrect() {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.startsWith("/baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsEnd_thenCorrect() {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.endsWith("articles"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
|
||||
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
|
||||
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
|
||||
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
|
||||
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
|
||||
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
|
||||
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
|
||||
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
|
||||
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
|
||||
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class AsyncEchoClient {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class);
|
||||
|
||||
private AsynchronousSocketChannel client;
|
||||
private Future<Void> future;
|
||||
private static AsyncEchoClient instance;
|
||||
|
||||
private AsyncEchoClient() {
|
||||
try {
|
||||
client = AsynchronousSocketChannel.open();
|
||||
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||
future = client.connect(hostAddress);
|
||||
start();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static AsyncEchoClient getInstance() {
|
||||
if (instance == null)
|
||||
instance = new AsyncEchoClient();
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void start() {
|
||||
try {
|
||||
future.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public String sendMessage(String message) {
|
||||
byte[] byteMsg = message.getBytes();
|
||||
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
|
||||
Future<Integer> writeResult = client.write(buffer);
|
||||
|
||||
try {
|
||||
writeResult.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
buffer.flip();
|
||||
Future<Integer> readResult = client.read(buffer);
|
||||
try {
|
||||
readResult.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String echo = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return echo;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
try {
|
||||
client.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
AsyncEchoClient client = AsyncEchoClient.getInstance();
|
||||
client.start();
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
String line;
|
||||
LOG.debug("Message to server:");
|
||||
while ((line = br.readLine()) != null) {
|
||||
String response = client.sendMessage(line);
|
||||
LOG.debug("response from server: " + response);
|
||||
LOG.debug("Message to server:");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncEchoIntegrationTest {
|
||||
|
||||
Process server;
|
||||
AsyncEchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException, InterruptedException {
|
||||
server = AsyncEchoServer2.start();
|
||||
client = AsyncEchoClient.getInstance();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServerClient_whenServerEchosMessage_thenCorrect() throws Exception {
|
||||
String resp1 = client.sendMessage("hello");
|
||||
String resp2 = client.sendMessage("world");
|
||||
assertEquals("hello", resp1);
|
||||
assertEquals("world", resp2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
server.destroy();
|
||||
client.stop();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class AsyncEchoServer {
|
||||
private AsynchronousServerSocketChannel serverChannel;
|
||||
private Future<AsynchronousSocketChannel> acceptResult;
|
||||
private AsynchronousSocketChannel clientChannel;
|
||||
|
||||
public AsyncEchoServer() {
|
||||
try {
|
||||
serverChannel = AsynchronousServerSocketChannel.open();
|
||||
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||
serverChannel.bind(hostAddress);
|
||||
acceptResult = serverChannel.accept();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void runServer() {
|
||||
try {
|
||||
clientChannel = acceptResult.get();
|
||||
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||
while (true) {
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
Future<Integer> readResult = clientChannel.read(buffer);
|
||||
|
||||
// do some computation
|
||||
|
||||
readResult.get();
|
||||
|
||||
buffer.flip();
|
||||
String message = new String(buffer.array()).trim();
|
||||
if (message.equals("bye")) {
|
||||
break; // while loop
|
||||
}
|
||||
buffer = ByteBuffer.wrap(new String(message).getBytes());
|
||||
Future<Integer> writeResult = clientChannel.write(buffer);
|
||||
|
||||
// do some computation
|
||||
writeResult.get();
|
||||
buffer.clear();
|
||||
|
||||
} // while()
|
||||
|
||||
clientChannel.close();
|
||||
serverChannel.close();
|
||||
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException | IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AsyncEchoServer server = new AsyncEchoServer();
|
||||
server.runServer();
|
||||
}
|
||||
|
||||
public static Process start() throws IOException, InterruptedException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||
String classpath = System.getProperty("java.class.path");
|
||||
String className = AsyncEchoServer.class.getCanonicalName();
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||
|
||||
return builder.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class AsyncEchoServer2 {
|
||||
private AsynchronousServerSocketChannel serverChannel;
|
||||
private AsynchronousSocketChannel clientChannel;
|
||||
|
||||
public AsyncEchoServer2() {
|
||||
try {
|
||||
serverChannel = AsynchronousServerSocketChannel.open();
|
||||
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||
serverChannel.bind(hostAddress);
|
||||
while (true) {
|
||||
|
||||
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
|
||||
|
||||
@Override
|
||||
public void completed(AsynchronousSocketChannel result, Object attachment) {
|
||||
if (serverChannel.isOpen())
|
||||
serverChannel.accept(null, this);
|
||||
clientChannel = result;
|
||||
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||
ReadWriteHandler handler = new ReadWriteHandler();
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
Map<String, Object> readInfo = new HashMap<>();
|
||||
readInfo.put("action", "read");
|
||||
readInfo.put("buffer", buffer);
|
||||
clientChannel.read(buffer, readInfo, handler);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {
|
||||
// process error
|
||||
}
|
||||
});
|
||||
try {
|
||||
System.in.read();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, Map<String, Object> attachment) {
|
||||
Map<String, Object> actionInfo = attachment;
|
||||
String action = (String) actionInfo.get("action");
|
||||
if ("read".equals(action)) {
|
||||
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
|
||||
buffer.flip();
|
||||
actionInfo.put("action", "write");
|
||||
clientChannel.write(buffer, actionInfo, this);
|
||||
buffer.clear();
|
||||
} else if ("write".equals(action)) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
actionInfo.put("action", "read");
|
||||
actionInfo.put("buffer", buffer);
|
||||
clientChannel.read(buffer, actionInfo, this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Map<String, Object> attachment) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new AsyncEchoServer2();
|
||||
}
|
||||
|
||||
public static Process start() throws IOException, InterruptedException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||
String classpath = System.getProperty("java.class.path");
|
||||
String className = AsyncEchoServer2.class.getCanonicalName();
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||
|
||||
return builder.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousFileChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncFileIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
final Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
final String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
|
||||
assertEquals(fileContent, "baeldung.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes read
|
||||
// attachment is the buffer
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
final String fileName = "temp";
|
||||
final Path path = Paths.get(fileName);
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final long position = 0;
|
||||
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
final Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
buffer.clear();
|
||||
|
||||
operation.get();
|
||||
|
||||
final String content = readContent(path);
|
||||
assertEquals("hello world", content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
|
||||
final String fileName = UUID.randomUUID().toString();
|
||||
final Path path = Paths.get(fileName);
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes written
|
||||
// attachment is the buffer
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
AsynchronousFileChannel fileChannel = null;
|
||||
try {
|
||||
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
final Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
final String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return fileContent;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.java.nio2.attributes;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.BasicFileAttributeView;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BasicAttribsIntegrationTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class);
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static BasicFileAttributes basicAttribs;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Path home = Paths.get(HOME);
|
||||
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
|
||||
basicAttribs = basicView.readAttributes();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileTimes_whenComparesThem_ThenCorrect() {
|
||||
FileTime created = basicAttribs.creationTime();
|
||||
FileTime modified = basicAttribs.lastModifiedTime();
|
||||
FileTime accessed = basicAttribs.lastAccessTime();
|
||||
|
||||
LOG.debug("Created: " + created);
|
||||
LOG.debug("Modified: " + modified);
|
||||
LOG.debug("Accessed: " + accessed);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenGetsFileSize_thenCorrect() {
|
||||
long size = basicAttribs.size();
|
||||
assertTrue(size > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfDirectory_thenCorrect() {
|
||||
boolean isDir = basicAttribs.isDirectory();
|
||||
assertTrue(isDir);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfFile_thenCorrect() {
|
||||
boolean isFile = basicAttribs.isRegularFile();
|
||||
assertFalse(isFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfSymLink_thenCorrect() {
|
||||
boolean isSymLink = basicAttribs.isSymbolicLink();
|
||||
assertFalse(isSymLink);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfOther_thenCorrect() {
|
||||
boolean isOther = basicAttribs.isOther();
|
||||
assertFalse(isOther);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaFileSizeUnitTest {
|
||||
private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11;
|
||||
private String filePath;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSize_thenCorrect() {
|
||||
final File file = new File(filePath);
|
||||
|
||||
final long size = getFileSize(file);
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException {
|
||||
final Path path = Paths.get(this.filePath);
|
||||
final FileChannel fileChannel = FileChannel.open(path);
|
||||
|
||||
final long fileSize = fileChannel.size();
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
|
||||
final File file = new File(filePath);
|
||||
|
||||
final long size = FileUtils.sizeOf(file);
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetReadableFileSize_thenCorrect() {
|
||||
final File file = new File(filePath);
|
||||
|
||||
final long size = getFileSize(file);
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size));
|
||||
}
|
||||
|
||||
private long getFileSize(final File file) {
|
||||
final long length = file.length();
|
||||
return length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
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.text.DecimalFormat;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaFolderSizeUnitTest {
|
||||
private final long EXPECTED_SIZE = 24;
|
||||
private String path;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
path = String.format("src%stest%sresources%stestFolder", separator, separator, separator);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeRecursive_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
final long size = getFolderSize(folder);
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException {
|
||||
final AtomicLong size = new AtomicLong(0);
|
||||
final Path folder = Paths.get(path);
|
||||
|
||||
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
|
||||
size.addAndGet(attrs.size());
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||
final Path folder = Paths.get(path);
|
||||
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
final long size = FileUtils.sizeOfDirectory(folder);
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetReadableSize_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
final long size = getFolderSize(folder);
|
||||
|
||||
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
|
||||
final int unitIndex = (int) (Math.log10(size) / 3);
|
||||
final double unitValue = 1 << (unitIndex * 10);
|
||||
|
||||
final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex];
|
||||
assertEquals(EXPECTED_SIZE + " B", readableSize);
|
||||
}
|
||||
|
||||
private long getFolderSize(final File folder) {
|
||||
long length = 0;
|
||||
final File[] files = folder.listFiles();
|
||||
|
||||
for (final File file : files) {
|
||||
if (file.isFile()) {
|
||||
length += file.length();
|
||||
} else {
|
||||
length += getFolderSize(file);
|
||||
}
|
||||
}
|
||||
return length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.mappedbytebuffer;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class MappedByteBufferUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
|
||||
// given
|
||||
CharBuffer charBuffer = null;
|
||||
Path pathToRead = getFileURIFromResources("fileToRead.txt");
|
||||
|
||||
// when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
// then
|
||||
assertNotNull(charBuffer);
|
||||
assertEquals(charBuffer.toString(), "This is a content of the file");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
|
||||
// given
|
||||
final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
|
||||
final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
|
||||
|
||||
// when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
mappedByteBuffer.put(Charset.forName("utf-8").encode(charBuffer));
|
||||
}
|
||||
}
|
||||
|
||||
// then
|
||||
final List<String> fileContent = Files.readAllLines(pathToWrite);
|
||||
assertEquals(fileContent.get(0), "This will be written to the file");
|
||||
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private final Path getFileURIFromResources(String fileName) throws Exception {
|
||||
final ClassLoader classLoader = getClass().getClassLoader();
|
||||
return Paths.get(classLoader.getResource(fileName).toURI());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.symlink;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SymLinkExampleManualTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCreateSymbolicLink() throws IOException {
|
||||
SymLinkExample example = new SymLinkExample();
|
||||
Path filePath = example.createTextFile();
|
||||
Path linkPath = Paths.get(".", "symbolic_link.txt");
|
||||
example.createSymbolicLink(linkPath, filePath);
|
||||
assertTrue(Files.isSymbolicLink(linkPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCreateHardLink() throws IOException {
|
||||
SymLinkExample example = new SymLinkExample();
|
||||
Path filePath = example.createTextFile();
|
||||
Path linkPath = Paths.get(".", "hard_link.txt");
|
||||
example.createHardLink(linkPath, filePath);
|
||||
assertFalse(Files.isSymbolicLink(linkPath));
|
||||
assertEquals(filePath.toFile()
|
||||
.length(),
|
||||
linkPath.toFile()
|
||||
.length());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.baeldung.core.exceptions;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
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"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Ignore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaReadFromFileUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read.in"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScanner_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read1.in"));
|
||||
scanner.useDelimiter(" ");
|
||||
|
||||
assertTrue(scanner.hasNext());
|
||||
assertEquals("Hello", scanner.next());
|
||||
assertEquals("world", scanner.next());
|
||||
assertEquals(1, scanner.nextInt());
|
||||
|
||||
scanner.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read2.in"));
|
||||
scanner.useDelimiter(",| ");
|
||||
|
||||
assertTrue(scanner.hasNextInt());
|
||||
assertEquals(2, scanner.nextInt());
|
||||
assertEquals(3, scanner.nextInt());
|
||||
assertEquals(4, scanner.nextInt());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithStreamTokenizer_thenCorrectTokens() throws IOException {
|
||||
final FileReader reader = new FileReader("src/test/resources/test_read3.in");
|
||||
final StreamTokenizer tokenizer = new StreamTokenizer(reader);
|
||||
|
||||
tokenizer.nextToken();
|
||||
assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype);
|
||||
assertEquals("Hello", tokenizer.sval);
|
||||
tokenizer.nextToken();
|
||||
assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype);
|
||||
assertEquals(1, tokenizer.nval, 0.0000001);
|
||||
|
||||
tokenizer.nextToken();
|
||||
assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype);
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithDataInputStream_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello";
|
||||
|
||||
String result;
|
||||
final DataInputStream reader = new DataInputStream(new FileInputStream("src/test/resources/test_read4.in"));
|
||||
result = reader.readUTF();
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, result);
|
||||
}
|
||||
|
||||
public void whenReadTwoFilesWithSequenceInputStream_thenCorrect() throws IOException {
|
||||
final int expected_value1 = 2000;
|
||||
final int expected_value2 = 5000;
|
||||
|
||||
final FileInputStream stream1 = new FileInputStream("src/test/resources/test_read5.in");
|
||||
final FileInputStream stream2 = new FileInputStream("src/test/resources/test_read6.in");
|
||||
|
||||
final SequenceInputStream sequence = new SequenceInputStream(stream1, stream2);
|
||||
final DataInputStream reader = new DataInputStream(sequence);
|
||||
|
||||
assertEquals(expected_value1, reader.readInt());
|
||||
assertEquals(expected_value2, reader.readInt());
|
||||
|
||||
reader.close();
|
||||
stream2.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // TODO
|
||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
||||
final String expected_value = "青空";
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
LOG.debug(currentLine);
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFileContentsIntoString_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world \n Test line \n";
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read8.in"));
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
String currentLine = reader.readLine();
|
||||
while (currentLine != null) {
|
||||
builder.append(currentLine);
|
||||
builder.append("\n");
|
||||
currentLine = reader.readLine();
|
||||
}
|
||||
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, builder.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithFileChannel_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
final FileChannel channel = reader.getChannel();
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
final ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
channel.read(buff);
|
||||
buff.flip();
|
||||
assertEquals(expected_value, new String(buff.array()));
|
||||
channel.close();
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadSmallFileJava7_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final Path path = Paths.get("src/test/resources/test_read.in");
|
||||
|
||||
final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0);
|
||||
assertEquals(expected_value, read);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadLargeFileJava7_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
|
||||
final Path path = Paths.get("src/test/resources/test_read.in");
|
||||
final BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset());
|
||||
final String line = reader.readLine();
|
||||
assertEquals(expected_value, line);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.CharSequenceReader;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.CharSource;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.FileWriteMode;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaReaderToXUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private static final int DEFAULT_SIZE = 1500000;
|
||||
|
||||
// tests - sandbox
|
||||
|
||||
// tests - Reader to String
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() throws IOException {
|
||||
final Reader reader = new StringReader("With Java 1");
|
||||
int intValueOfChar;
|
||||
String targetString = "";
|
||||
while ((intValueOfChar = reader.read()) != -1) {
|
||||
targetString += (char) intValueOfChar;
|
||||
}
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java 1");
|
||||
final char[] arr = new char[8 * 1024];
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
|
||||
buffer.append(arr, 0, numCharsRead);
|
||||
}
|
||||
initialReader.close();
|
||||
final String targetString = buffer.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException {
|
||||
final Reader initialReader = CharSource.wrap("With Google Guava").openStream();
|
||||
final String targetString = CharStreams.toString(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Apache Commons");
|
||||
final String targetString = IOUtils.toString(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader WRITE TO File
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("Some text");
|
||||
|
||||
int intValueOfChar;
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
while ((intValueOfChar = initialReader.read()) != -1) {
|
||||
buffer.append((char) intValueOfChar);
|
||||
}
|
||||
initialReader.close();
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
targetFile.createNewFile();
|
||||
|
||||
final Writer targetFileWriter = new FileWriter(targetFile);
|
||||
targetFileWriter.write(buffer.toString());
|
||||
targetFileWriter.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("Some text");
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
com.google.common.io.Files.touch(targetFile);
|
||||
final CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND);
|
||||
charSink.writeFrom(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new CharSequenceReader("CharSequenceReader extends Reader");
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
FileUtils.touch(targetFile);
|
||||
final byte[] buffer = IOUtils.toByteArray(initialReader);
|
||||
FileUtils.writeByteArrayToFile(targetFile, buffer);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader to byte[]
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charArray = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charArray, 0, charArray.length)) != -1) {
|
||||
builder.append(charArray, 0, numCharsRead);
|
||||
}
|
||||
final byte[] targetArray = builder.toString().getBytes();
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final Reader initialReader = CharSource.wrap("With Google Guava").openStream();
|
||||
|
||||
final byte[] targetArray = CharStreams.toString(initialReader).getBytes();
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final StringReader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final byte[] targetArray = IOUtils.toByteArray(initialReader);
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader to InputStream
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charBuffer = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
|
||||
builder.append(charBuffer, 0, numCharsRead);
|
||||
}
|
||||
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes());
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Guava");
|
||||
|
||||
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes());
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
String initialString = "With Commons IO";
|
||||
final Reader initialReader = new StringReader(initialString);
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
|
||||
|
||||
final String finalString = IOUtils.toString(targetStream);
|
||||
assertThat(finalString, equalTo(initialString));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
// tests - Reader to InputStream with encoding
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charBuffer = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
|
||||
builder.append(charBuffer, 0, numCharsRead);
|
||||
}
|
||||
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Guava");
|
||||
|
||||
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes(Charsets.UTF_8));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
|
||||
String initialString = "With Commons IO";
|
||||
final Reader initialReader = new StringReader(initialString);
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
|
||||
|
||||
String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
|
||||
assertThat(finalString, equalTo(initialString));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class JavaXToByteArrayUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - X to Byte Array
|
||||
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.CharSequenceReader;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharSource;
|
||||
|
||||
public class JavaXToReaderUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - String to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Plain Java";
|
||||
final Reader targetReader = new StringReader(initialString);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Google Guava";
|
||||
final Reader targetReader = CharSource.wrap(initialString).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Apache Commons IO";
|
||||
final Reader targetReader = new CharSequenceReader(initialString);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - byte array to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "Hello world!".getBytes();
|
||||
final Reader targetReader = new StringReader(new String(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava2_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "Hello world!".getBytes();
|
||||
final Reader targetReader = new InputStreamReader(new ByteArrayInputStream(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Guava".getBytes();
|
||||
final String bufferString = new String(initialArray);
|
||||
final Reader targetReader = CharSource.wrap(bufferString).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Commons IO".getBytes();
|
||||
final Reader targetReader = new CharSequenceReader(new String(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - File to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
initialFile.createNewFile();
|
||||
final Reader targetReader = new FileReader(initialFile);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
com.google.common.io.Files.touch(initialFile);
|
||||
final Reader targetReader = com.google.common.io.Files.newReader(initialFile, Charset.defaultCharset());
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
FileUtils.touch(initialFile);
|
||||
FileUtils.write(initialFile, "With Commons IO");
|
||||
final byte[] buffer = FileUtils.readFileToByteArray(initialFile);
|
||||
final Reader targetReader = new CharSequenceReader(new String(buffer));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - InputStream to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());
|
||||
final Reader targetReader = new InputStreamReader(initialStream);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();
|
||||
final byte[] buffer = ByteStreams.toByteArray(initialStream);
|
||||
final Reader targetReader = CharSource.wrap(new String(buffer)).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = IOUtils.toInputStream("With Commons IO");
|
||||
final byte[] buffer = IOUtils.toByteArray(initialStream);
|
||||
final Reader targetReader = new CharSequenceReader(new String(buffer));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
13
core-java-modules/core-java-io/src/test/resources/.gitignore
vendored
Normal file
13
core-java-modules/core-java-io/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
...Continues
|
||||
@@ -0,0 +1,2 @@
|
||||
Mary Kom,Unbreakable
|
||||
Kapil Isapuari,Farishta
|
||||
|
@@ -0,0 +1,4 @@
|
||||
# this is sample property file for PropertiesLoaderTest configuration needs
|
||||
! this is also a comment
|
||||
sampleConfEntry = sample String value
|
||||
colonSeparatedEntry : colon separated entry value
|
||||
@@ -0,0 +1,2 @@
|
||||
files will be copied here and then deleted
|
||||
remove `file.delete()` to see the files here
|
||||
@@ -0,0 +1 @@
|
||||
apache
|
||||
@@ -0,0 +1 @@
|
||||
channel
|
||||
@@ -0,0 +1 @@
|
||||
files
|
||||
@@ -0,0 +1 @@
|
||||
stream
|
||||
178691
core-java-modules/core-java-io/src/test/resources/dictionary.in
Normal file
178691
core-java-modules/core-java-io/src/test/resources/dictionary.in
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
baeldung.com
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1 @@
|
||||
<xml></xml>
|
||||
@@ -0,0 +1 @@
|
||||
<xml></xml>
|
||||
@@ -0,0 +1 @@
|
||||
Hello World from fileTest.txt!!!
|
||||
@@ -0,0 +1 @@
|
||||
This is a content of the file
|
||||
@@ -0,0 +1 @@
|
||||
This example shows how we can delete the file contents without deleting the file
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 190 KiB |
@@ -0,0 +1 @@
|
||||
With Commons IO
|
||||
@@ -0,0 +1 @@
|
||||
This is a sample txt file for unit test ListFilesUnitTest
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1 @@
|
||||
<xml></xml>
|
||||
BIN
core-java-modules/core-java-io/src/test/resources/product.png
Normal file
BIN
core-java-modules/core-java-io/src/test/resources/product.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
@@ -0,0 +1 @@
|
||||
Hello World
|
||||
@@ -0,0 +1,2 @@
|
||||
111
|
||||
222
|
||||
@@ -0,0 +1,2 @@
|
||||
Hello
|
||||
World
|
||||
@@ -0,0 +1 @@
|
||||
Hello World
|
||||
@@ -0,0 +1 @@
|
||||
Some textSome text
|
||||
@@ -0,0 +1 @@
|
||||
Test of JNDI on file.
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
@@ -0,0 +1 @@
|
||||
Hello world !
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
@@ -0,0 +1 @@
|
||||
Hello world 1
|
||||
@@ -0,0 +1 @@
|
||||
2,3 4
|
||||
@@ -0,0 +1 @@
|
||||
Hello 1
|
||||
BIN
core-java-modules/core-java-io/src/test/resources/test_read4.in
Normal file
BIN
core-java-modules/core-java-io/src/test/resources/test_read4.in
Normal file
Binary file not shown.
@@ -0,0 +1 @@
|
||||
青空
|
||||
@@ -0,0 +1,2 @@
|
||||
Hello world
|
||||
Test line
|
||||
@@ -0,0 +1 @@
|
||||
John,Adam-Tom
|
||||
@@ -0,0 +1,2 @@
|
||||
Hello world
|
||||
Hi, John
|
||||
@@ -0,0 +1 @@
|
||||
this
|
||||
@@ -0,0 +1 @@
|
||||
Some StringProduct name is iPhone and its price is 1000 $
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user