JAVA-22516 Split or move core-java-io-apis-2 module (moved-1) (#14361)

* JAVA-22516 Split or move core-java-io-apis-2 module (moved-1)

* JAVA-22516 Adding back the file after fixing the conflicts

---------

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1
2023-07-14 20:30:39 +03:00
committed by GitHub
parent 88e25373b8
commit 5142770066
33 changed files with 461 additions and 369 deletions

View File

@@ -0,0 +1,29 @@
package com.baeldung.scanner;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Scanner;
public class DateScanner {
LocalDate scanToLocalDate(String input) {
try (Scanner scanner = new Scanner(input)) {
String dateString = scanner.next();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return LocalDate.parse(dateString, formatter);
}
}
Date scanToDate(String input) throws ParseException {
try (Scanner scanner = new Scanner(input)) {
String dateString = scanner.next();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.parse(dateString);
}
}
}

View File

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

View File

@@ -0,0 +1,56 @@
package com.baeldung.scanner;
import java.util.Scanner;
public class NextLineAfterNextMethods {
private static void produceSkippingNextLineMethod() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your first name: ");
String firstName = scanner.nextLine(); // Skipped because it reads the remaining newline character
System.out.println(age + ":" + firstName);
}
}
private static void fixSkippingNextLineMethodV1() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter your first name: ");
String firstName = scanner.nextLine();
System.out.println(age + ":" + firstName);
}
}
private static void fixSkippingNextLineMethodV2() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your age: ");
int age = Integer.parseInt(scanner.nextLine());
System.out.print("Enter your first name: ");
String firstName = scanner.nextLine();
System.out.println(age + ":" + firstName);
}
}
private static void fixSkippingNextLineMethodV3() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.skip("\r\n");
System.out.print("Enter your first name: ");
String firstName = scanner.nextLine();
System.out.println(age + ":" + firstName);
}
}
public static void main(String[] args) {
produceSkippingNextLineMethod();
fixSkippingNextLineMethodV1();
fixSkippingNextLineMethodV2();
fixSkippingNextLineMethodV3();
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.scanner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ScannerNoSuchElementException {
public static String readFileV1(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile)) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.nextLine();
}
}
public static String readFileV2(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile)) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.hasNextLine() ? scanner.nextLine() : "";
}
}
public static String readFileV3(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile) || Files.size(pathFile) == 0) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.nextLine();
}
}
public static String readFileV4(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile)) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.nextLine();
} catch (NoSuchElementException exception) {
return "";
}
}
}

View File

@@ -0,0 +1,71 @@
package com.baeldung.emptyfile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class CheckFileIsEmptyUnitTest {
@Test
void whenTheFileIsEmpty_thenFileLengthIsZero(@TempDir Path tempDir) throws IOException {
File emptyFile = tempDir.resolve("an-empty-file.txt")
.toFile();
emptyFile.createNewFile();
assertTrue(emptyFile.exists());
assertEquals(0, emptyFile.length());
}
@Test
void whenFileDoesNotExist_thenFileLengthIsZero(@TempDir Path tempDir) {
File aNewFile = tempDir.resolve("a-new-file.txt")
.toFile();
assertFalse(aNewFile.exists());
assertEquals(0, aNewFile.length());
}
boolean isFileEmpty(File file) {
if (!file.exists()) {
throw new IllegalArgumentException("Cannot check the file length. The file is not found: " + file.getAbsolutePath());
}
return file.length() == 0;
}
@Test
void whenTheFileDoesNotExist_thenIsFilesEmptyThrowsException(@TempDir Path tempDir) {
File aNewFile = tempDir.resolve("a-new-file.txt")
.toFile();
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> isFileEmpty(aNewFile));
assertEquals(ex.getMessage(), "Cannot check the file length. The file is not found: " + aNewFile.getAbsolutePath());
}
@Test
void whenTheFileIsEmpty_thenIsFilesEmptyReturnsTrue(@TempDir Path tempDir) throws IOException {
File emptyFile = tempDir.resolve("an-empty-file.txt")
.toFile();
emptyFile.createNewFile();
assertTrue(isFileEmpty(emptyFile));
}
@Test
void whenTheFileIsEmpty_thenFilesSizeReturnsTrue(@TempDir Path tempDir) throws IOException {
Path emptyFilePath = tempDir.resolve("an-empty-file.txt");
Files.createFile(emptyFilePath);
assertEquals(0, Files.size(emptyFilePath));
}
@Test
void whenTheFileDoesNotExist_thenFilesSizeThrowsException(@TempDir Path tempDir) {
Path aNewFilePath = tempDir.resolve("a-new-file.txt");
assertThrows(NoSuchFileException.class, () -> Files.size(aNewFilePath));
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;
class DateScannerUnitTest {
@Test
void whenScanToLocalDate_ThenCorrectLocalDate() {
String dateString = "2018-09-09";
assertEquals(LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd")), new DateScanner().scanToLocalDate(dateString));
}
@Test
void whenScanToDate_ThenCorrectDate() throws ParseException {
String dateString = "2018-09-09";
assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse(dateString), new DateScanner().scanToDate(dateString));
}
}

View File

@@ -0,0 +1,97 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class InputWithSpacesUnitTest {
@Test
void whenValuesContainSpaces_thenNextBreaksTheValue() {
String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);
String name = sc.next();
String description = sc.next();
assertEquals("Michael", name);
assertEquals("Jackson", description);
}
@Test
void whenOneValuePerLineUsingNextLine_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);
String name = sc.nextLine();
String description = sc.nextLine();
assertEquals("Michael Jackson", name);
assertEquals("He was the 'King of Pop'.", description);
}
@Test
void whenOneValuePerLineUsingNewLineAsDelimiter_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter("\\n");
String name = sc.next();
String description = sc.next();
assertEquals("Michael Jackson", name);
assertEquals("He was the 'King of Pop'.", description);
}
@Test
void whenValuesAreSeparatedByCommaUsingSplit_thenGetExpectedResult() {
String input = "Michael Jackson, Whitney Houston, John Lennon\n";
Scanner sc = new Scanner(input);
String[] names = sc.nextLine()
.split(", ");
assertArrayEquals(new String[] { "Michael Jackson", "Whitney Houston", "John Lennon" }, names);
}
@Test
void whenValuesAreSeparatedByCommaSettingDelimiterWithoutNewline_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
.append("Elvis Presley\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter(", ");
List<String> names = new ArrayList<>();
while (sc.hasNext()) {
names.add(sc.next());
}
//assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names); <-- Fail
assertEquals(3, names.size());
assertEquals("John Lennon\nElvis Presley\n", names.get(2));
}
@Test
void whenValuesAreSeparatedByCommaSettingDelimiter_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
.append("Elvis Presley\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter(", |\\n");
List<String> names = new ArrayList<>();
while (sc.hasNext()) {
names.add(sc.next());
}
assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names);
}
}

View File

@@ -0,0 +1,200 @@
package com.baeldung.scanner;
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.NoSuchElementException;
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();
}
@Test(expected = NoSuchElementException.class)
public void givenClosingScanner_whenReading_thenThrowException() throws IOException {
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
final Scanner scanner = new Scanner(inputStream);
scanner.next();
scanner.close();
final Scanner scanner2 = new Scanner(inputStream);
scanner2.next();
scanner2.close();
}
}

View File

@@ -0,0 +1,85 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
public class NextLineVsNextIntUnitTest {
@Test
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
String input = "42\n";
//nextLine()
Scanner sc1 = new Scanner(input);
int num1 = Integer.parseInt(sc1.nextLine());
assertEquals(42, num1);
//nextInt()
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
}
@Test
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
String input = "Nan\n";
//nextLine() -> NumberFormatException
Scanner sc1 = new Scanner(input);
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
//nextInt() -> InputMismatchException
Scanner sc2 = new Scanner(input);
assertThrows(InputMismatchException.class, sc2::nextInt);
}
@Test
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
String input = "42 is a magic number\n";
//nextInt() to read '42'
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
// call nextInt() again on "is"
assertThrows(InputMismatchException.class, sc2::nextInt);
String theNextToken = sc2.next();
assertEquals("is", theNextToken);
theNextToken = sc2.next();
assertEquals("a", theNextToken);
}
@Test
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
String input = new StringBuilder().append("42\n")
.append("It is a magic number.\n")
.toString();
//nextLine()
Scanner sc1 = new Scanner(input);
int num1 = Integer.parseInt(sc1.nextLine());
String nextLineText1 = sc1.nextLine();
assertEquals(42, num1);
assertEquals("It is a magic number.", nextLineText1);
//nextInt()
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
// nextInt() leaves the newline character (\n) behind
String nextLineText2 = sc2.nextLine();
assertEquals("", nextLineText2);
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
class NextVsNextLineUnitTest {
@Test
void givenInput_whenUsingNextMethod_thenReturnToken() {
String input = "Hello world";
try (Scanner scanner = new Scanner(input)) {
assertEquals("Hello", scanner.next());
assertEquals("world", scanner.next());
}
}
@Test
void givenInput_whenUsingNextMethodWithCustomDelimiter_thenReturnToken() {
String input = "Hello :world";
try (Scanner scanner = new Scanner(input)) {
scanner.useDelimiter(":");
assertEquals("Hello ", scanner.next());
assertEquals("world", scanner.next());
}
}
@Test
void givenInput_whenUsingNextLineMethod_thenReturnEntireLine() {
String input = "Hello world\nWelcome to baeldung.com";
try (Scanner scanner = new Scanner(input)) {
assertEquals("Hello world", scanner.nextLine());
assertEquals("Welcome to baeldung.com", scanner.nextLine());
}
}
@Test
void givenInput_whenUsingNextLineWithCustomDelimiter_thenIgnoreDelimiter() {
String input = "Hello:world\nWelcome:to baeldung.com";
try (Scanner scanner = new Scanner(input)) {
scanner.useDelimiter(":");
assertEquals("Hello:world", scanner.nextLine());
assertEquals("Welcome:to baeldung.com", scanner.nextLine());
}
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
public class ScanACharacterUnitTest {
// given - input scanner source, no need to scan from console
String input = new StringBuilder().append("abc\n")
.append("mno\n")
.append("xyz\n")
.toString();
@Test
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
Scanner sc = new Scanner(input);
char c = sc.next().charAt(0);
assertEquals('a', c);
}
@Test
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
Scanner sc = new Scanner(input);
char c = sc.findInLine(".").charAt(0);
assertEquals('a', c);
}
@Test
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
Scanner sc = new Scanner(input);
char c = sc.useDelimiter("").next().charAt(0);
assertEquals('a', c);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
class ScannerNoSuchElementExceptionUnitTest {
@Test
void givenEmptyFile_whenUsingReadFileV1_thenThrowException() {
Exception exception = assertThrows(NoSuchElementException.class, () -> {
ScannerNoSuchElementException.readFileV1("src/test/resources/emptyFile.txt");
});
assertEquals("No line found", exception.getMessage());
}
@Test
void givenEmptyFile_whenUsingReadFileV2_thenSuccess() throws IOException {
String emptyLine = ScannerNoSuchElementException.readFileV2("src/test/resources/emptyFile.txt");
assertEquals("", emptyLine);
}
@Test
void givenEmptyFile_whenUsingReadFileV3_thenSuccess() throws IOException {
String emptyLine = ScannerNoSuchElementException.readFileV3("src/test/resources/emptyFile.txt");
assertEquals("", emptyLine);
}
@Test
void givenEmptyFile_whenUsingReadFileV4_thenSuccess() throws IOException {
String emptyLine = ScannerNoSuchElementException.readFileV4("src/test/resources/emptyFile.txt");
assertEquals("", emptyLine);
}
}

View File

@@ -0,0 +1,107 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.ObjectArrays;
public class ScannerToArrayUnitTest {
@Test
void whenMultipleElementsInOneLine_thenGetExpectedArray() {
String input = "Java Kotlin Ruby Python Go\n";
String[] expected = new String[] { "Java", "Kotlin", "Ruby", "Python", "Go" };
// scanner.next()
Scanner scanner1 = new Scanner(input);
String[] result1 = new String[5];
int i = 0;
while (i < result1.length) {
result1[i] = scanner1.next();
i++;
}
assertArrayEquals(expected, result1);
//split()
Scanner scanner2 = new Scanner(input);
String[] result2 = scanner2.nextLine()
.split("\\s+");
assertArrayEquals(expected, result2);
}
@Test
void whenOneElementPerLine_thenGetExpectedArray() {
String input = new StringBuilder().append("Baeldung Java\n")
.append("Baeldung Kotlin\n")
.append("Baeldung Linux\n")
.toString();
String[] expected = new String[] { "Baeldung Java", "Baeldung Kotlin", "Baeldung Linux" };
String[] result = new String[3];
Scanner scanner = new Scanner(input);
int i = 0;
while (i < result.length) {
result[i] = scanner.nextLine();
i++;
}
assertArrayEquals(expected, result);
}
@Test
void whenOneElementPerLine_thenGetExpectedList() {
String input = new StringBuilder().append("Baeldung Java\n")
.append("Baeldung Kotlin\n")
.append("Baeldung Linux\n")
.toString();
List<String> expected = Lists.newArrayList("Baeldung Java", "Baeldung Kotlin", "Baeldung Linux");
List<String> result = new ArrayList<>();
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
result.add(scanner.nextLine());
}
assertEquals(expected, result);
}
@Test
void whenEveryTokenIsAnElement_thenGetExpectedList() {
String input = new StringBuilder().append("Linux Windows MacOS\n")
.append("Java Kotlin Python Go\n")
.toString();
List<String> expected = Lists.newArrayList("Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go");
List<String> result = new ArrayList<>();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
result.add(scanner.next());
}
assertEquals(expected, result);
}
@Test
void whenEveryTokenIsAnElement_thenGetExpectedArray() {
String input = new StringBuilder().append("Linux Windows MacOS\n")
.append("Java Kotlin Python Go\n")
.toString();
String[] expected = new String[] { "Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go" };
String[] result = new String[] {};
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
String[] lineInArray = scanner.nextLine()
.split("\\s+");
result = ObjectArrays.concat(result, lineInArray, String.class);
}
assertArrayEquals(expected, result);
}
}

View File

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

View File

@@ -0,0 +1 @@
Hello world

View File

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

View File

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