BAEL-6465: How to handle NoSuchElementException when reading a file through a Scanner ? (#13999)

This commit is contained in:
Azhwani
2023-05-28 11:06:59 +02:00
committed by GitHub
parent d42b1d05b1
commit c9cc5bbefd
3 changed files with 101 additions and 0 deletions

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 "";
}
}
}