99import java .nio .file .Path ;
1010import java .util .Collection ;
1111import java .util .List ;
12+ import java .util .Optional ;
1213
1314public class SNBT {
1415 private static boolean shouldSortKeysOnWrite = false ;
@@ -23,10 +24,28 @@ public static SNBTCompoundTag readLines(List<String> lines) {
2324 return SNBTParser .read (lines );
2425 }
2526
27+ /**
28+ * Attempt to read an SNBT compound from a file
29+ * @param path the path to the SNBT file
30+ * @return the SNBT compound tag
31+ */
2632 public static SNBTCompoundTag tryRead (Path path ) throws IOException {
2733 return readLines (Files .readAllLines (path , StandardCharsets .UTF_8 ));
2834 }
2935
36+ /**
37+ * Same as {@link #tryRead(Path)} but returns an empty optional on failure instead of throwing an exception
38+ * @param file the file to read
39+ * @return an optional SNBT compound tag
40+ */
41+ public static Optional <SNBTCompoundTag > tryReadOptional (Path file ) {
42+ try {
43+ return Optional .of (tryRead (file ));
44+ } catch (IOException ex ) {
45+ return Optional .empty ();
46+ }
47+ }
48+
3049 public static void tryWrite (Path path , CompoundTag tag ) throws IOException {
3150 if (Files .notExists (path .getParent ())) {
3251 Files .createDirectories (path .getParent ());
@@ -55,27 +74,6 @@ public static List<String> writeLines(CompoundTag nbt) {
5574 return builder .lines ;
5675 }
5776
58- /**
59- * Don't use this anymore
60- * @param path path to write to
61- * @param nbt nbt compound to write
62- * @return true if config was written
63- * @deprecated use {@link #tryWrite(Path, CompoundTag)}
64- */
65- @ Deprecated
66- public static boolean write (Path path , CompoundTag nbt ) {
67- try {
68- if (Files .notExists (path .getParent ())) {
69- Files .createDirectories (path .getParent ());
70- }
71-
72- Files .write (path , writeLines (nbt ));
73- return true ;
74- } catch (Exception ex ) {
75- return false ;
76- }
77- }
78-
7977 private static void append (SNBTBuilder builder , @ Nullable Tag nbt ) {
8078 switch (nbt ) {
8179 case null -> builder .print ("null" );
0 commit comments