Skip to content

Instantly share code, notes, and snippets.

@Anebrithien
Created August 15, 2020 17:41
Show Gist options
  • Save Anebrithien/1ef0c4debf319a88f3312992e85c3642 to your computer and use it in GitHub Desktop.
Save Anebrithien/1ef0c4debf319a88f3312992e85c3642 to your computer and use it in GitHub Desktop.
Just a simple autoClose test
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadFile {
private static final long HEAD_LINES = 3;
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
do {
System.out.print("Input text file absolute name(Press Ctrl+C to exit): ");
final String nextLine = scanner.nextLine();
System.out.println(nextLine);
final Path path = Paths.get(nextLine);
if (path.toFile().exists()) {
System.out.println(path + " is exist, try to read it as text file");
if (isCloseMode(args)) {
System.out.println("read first " + HEAD_LINES + "lines with close():");
Optional.ofNullable(readWithClose(path, HEAD_LINES))
.map(strings -> String.join("\n", strings))
.ifPresent(System.out::println);
} else {
System.out.println("read first " + HEAD_LINES + "lines without close():");
Optional.ofNullable(readWithOutClose(path, HEAD_LINES))
.map(strings -> String.join("\n", strings))
.ifPresent(System.out::println);
}
System.out.println("\n==========\n==========");
} else {
System.out.println(path + " is not exist, try again!");
}
} while (scanner.hasNext());
}
private static boolean isCloseMode(String[] args) {
return args != null && args.length > 0;
}
private static List<String> readWithOutClose(Path filePath, long headLines) {
try {
return Files.lines(filePath)
.limit(headLines)
.collect(Collectors.toList());
} catch (IOException e) {
System.err.println(String.format("read file '%s' failed: %s", filePath, e));
return null;
}
}
private static List<String> readWithClose(Path filePath, long headLines) {
try (Stream<String> stream = Files.lines(filePath)) {
return stream
.limit(headLines)
.collect(Collectors.toList());
} catch (IOException e) {
System.err.println(String.format("read file '%s' failed: %s", filePath, e));
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment