diff options
author | ArghKevin <kagheli@student.sdccd.edu> | 2024-05-16 02:02:20 -0700 |
---|---|---|
committer | ArghKevin <kagheli@student.sdccd.edu> | 2024-05-16 02:02:20 -0700 |
commit | 05daaff79736c779b8ff8a7a0867ffc8886b9769 (patch) | |
tree | 7b9f6dccc2888fd60c2594d8189944c15f400daa | |
parent | dad2361ea75d9198fbf17f8f274c05f00c378898 (diff) |
Fixed bug reading popularity.json via File.readAllLines and String.join.
-rw-r--r-- | src/Reader.java | 23 |
1 files changed, 9 insertions, 14 deletions
diff --git a/src/Reader.java b/src/Reader.java index 024088e..cdad0cc 100644 --- a/src/Reader.java +++ b/src/Reader.java @@ -1,11 +1,14 @@ import java.io.*; -import java.util.Scanner; +import java.nio.file.Files; +import java.nio.charset.Charset; +import java.util.List; /* * @author * Kian Agheli * * References: + * https://www.baeldung.com/java-scanner * * Date: * 2024-05-08 @@ -21,24 +24,16 @@ class Reader { public Reader(File file) { this.file = file; contents = null; - Scanner scan = null; try { - /* Scan over the contents of the input file. */ - scan = new Scanner(file); - /* Save to object. */ - contents = scan.nextLine() + "\n"; - while (scan.hasNextLine()) { - contents += scan.nextLine(); - contents += "\n"; - } + /* Read the contents of the input file. Assume UTF-8. + Files.readAllLines() automatically closes the file. */ + List<String> lines = Files.readAllLines(file.toPath(), Charset.forName("UTF-8")); + /* Combine list into one string. */ + contents = String.join("\n", lines); /* On exception, exit. */ } catch (Exception e) { System.out.println(e.getMessage()); System.exit(1); - } finally { - if (scan != null) { - scan.close(); - } } } |