Skip to content

Commit

Permalink
Use one file handle for state writing
Browse files Browse the repository at this point in the history
  • Loading branch information
jojoe77777 committed Apr 11, 2023
1 parent 2434096 commit 10e1fb7
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/main/java/me/voidxwalker/worldpreview/StateOutputHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import org.apache.logging.log4j.Level;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
Expand All @@ -21,6 +21,8 @@ public final class StateOutputHelper {
public static boolean titleHasEverLoaded = false;
private static String lastOutput = "";

private static RandomAccessFile stateFile;


private StateOutputHelper() {
}
Expand All @@ -44,8 +46,12 @@ public static void outputState(String string) {

private static void outputStateInternal(String string) {
try {
// Java 11+ method
Files.write(OUT_PATH, string.getBytes(StandardCharsets.UTF_8));
if(stateFile == null){ // opening file only once is better for performance
stateFile = new RandomAccessFile(OUT_PATH.toString(), "rw");
}
stateFile.setLength(0); // clear existing file contents
stateFile.seek(0); // move pointer back to start of file
stateFile.write(string.getBytes(StandardCharsets.UTF_8));
WorldPreview.log(Level.INFO, "WorldPreview State: " + string);
} catch (IOException ignored) {
WorldPreview.log(Level.ERROR, "Failed to write state output!");
Expand Down

0 comments on commit 10e1fb7

Please sign in to comment.