简化 FileUtils (#4119)

This commit is contained in:
Glavo 2025-07-26 20:10:38 +08:00 committed by GitHub
parent 43b769923b
commit 46502875c5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
40 changed files with 76 additions and 136 deletions

View File

@ -170,7 +170,7 @@ public class HMCLGameRepository extends DefaultGameRepository {
}
Files.copy(fromJson, toJson);
FileUtils.writeText(toJson.toFile(), JsonUtils.GSON.toJson(fromVersion.setId(dstId)));
FileUtils.writeText(toJson, JsonUtils.GSON.toJson(fromVersion.setId(dstId)));
VersionSetting oldVersionSetting = getVersionSetting(srcId).clone();
GameDirectoryType originalGameDirType = oldVersionSetting.getGameDirType();
@ -194,7 +194,7 @@ public class HMCLGameRepository extends DefaultGameRepository {
File file = getLocalVersionSettingFile(id);
if (file.exists())
try {
VersionSetting versionSetting = GSON.fromJson(FileUtils.readText(file), VersionSetting.class);
VersionSetting versionSetting = GSON.fromJson(Files.readString(file.toPath()), VersionSetting.class);
initLocalVersionSetting(id, versionSetting);
} catch (Exception ex) {
// If [JsonParseException], [IOException] or [NullPointerException] happens, the json file is malformed and needed to be recreated.
@ -427,7 +427,7 @@ public class HMCLGameRepository extends DefaultGameRepository {
File json = getModpackConfiguration(version);
if (json.exists()) {
try {
String jsonText = FileUtils.readText(json);
String jsonText = Files.readString(json.toPath());
ModpackConfiguration<?> modpackConfiguration = JsonUtils.GSON.fromJson(jsonText, ModpackConfiguration.class);
ModpackProvider provider = ModpackHelper.getProviderByType(modpackConfiguration.getType());
if (provider != null) provider.injectLaunchOptions(jsonText, builder);

View File

@ -28,10 +28,10 @@ import org.jackhuang.hmcl.setting.Profile;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.CompressingUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -66,7 +66,7 @@ public final class HMCLModpackInstallTask extends Task<Void> {
ModpackConfiguration<Modpack> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(Modpack.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(Modpack.class));
if (!HMCLModpackProvider.INSTANCE.getName().equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a HMCL modpack. Cannot update this version.");

View File

@ -140,7 +140,7 @@ public final class ModpackHelper {
throw new FileNotFoundException(file.getPath());
else
try {
return JsonUtils.GSON.fromJson(FileUtils.readText(file), ModpackConfiguration.class);
return JsonUtils.GSON.fromJson(Files.readString(file.toPath()), ModpackConfiguration.class);
} catch (JsonParseException e) {
throw new IOException("Malformed modpack configuration");
}

View File

@ -24,7 +24,6 @@ import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.gson.TolerableValidationException;
import org.jackhuang.hmcl.util.gson.Validation;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.JarUtils;
import java.io.IOException;
@ -73,7 +72,7 @@ public final class AuthlibInjectorServers implements Validation {
if (ConfigHolder.isNewlyCreated() && Files.exists(configLocation)) {
AuthlibInjectorServers configInstance;
try {
String content = FileUtils.readText(configLocation);
String content = Files.readString(configLocation);
configInstance = JsonUtils.GSON.fromJson(content, AuthlibInjectorServers.class);
} catch (IOException | JsonParseException e) {
LOG.warning("Malformed authlib-injectors.json", e);

View File

@ -158,7 +158,7 @@ public final class ConfigHolder {
LOG.warning("Failed to get owner");
}
try {
String content = FileUtils.readText(configLocation);
String content = Files.readString(configLocation);
Config deserialized = Config.fromJson(content);
if (deserialized == null) {
LOG.info("Config is empty");
@ -180,7 +180,7 @@ public final class ConfigHolder {
private static GlobalConfig loadGlobalConfig() throws IOException {
if (Files.exists(GLOBAL_CONFIG_PATH)) {
try {
String content = FileUtils.readText(GLOBAL_CONFIG_PATH);
String content = Files.readString(GLOBAL_CONFIG_PATH);
GlobalConfig deserialized = GlobalConfig.fromJson(content);
if (deserialized == null) {
LOG.info("Config is empty");

View File

@ -23,7 +23,6 @@ import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import org.jackhuang.hmcl.ui.FXUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.nio.charset.Charset;
@ -68,7 +67,7 @@ public final class StyleSheets {
Path temp = Files.createTempFile("hmcl", ".css");
// For JavaFX 17 or earlier, CssParser uses the default charset
// https://bugs.openjdk.org/browse/JDK-8279328
FileUtils.writeText(temp, styleSheet, Charset.defaultCharset());
Files.writeString(temp, styleSheet, Charset.defaultCharset());
temp.toFile().deleteOnExit();
return temp.toUri().toString();
} catch (IOException | NullPointerException e) {

View File

@ -32,7 +32,6 @@ import org.jackhuang.hmcl.ui.construct.MessageDialogPane.MessageType;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.SwingUtils;
import org.jackhuang.hmcl.util.TaskCancellationAction;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.JarUtils;
import org.jackhuang.hmcl.java.JavaRuntime;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
@ -265,7 +264,7 @@ public final class UpdateHandler {
Path hmclVersionJson = Metadata.HMCL_GLOBAL_DIRECTORY.resolve("hmclver.json");
if (Files.isRegularFile(hmclVersionJson)) {
try {
Map<?, ?> content = new Gson().fromJson(FileUtils.readText(hmclVersionJson), Map.class);
Map<?, ?> content = new Gson().fromJson(Files.readString(hmclVersionJson), Map.class);
Object ver = content.get("ver");
if (ver instanceof String && ((String) ver).startsWith("3.")) {
Files.delete(hmclVersionJson);

View File

@ -23,7 +23,6 @@ import org.jackhuang.hmcl.game.LaunchOptions;
import org.jackhuang.hmcl.java.JavaInfo;
import org.jackhuang.hmcl.game.Log;
import org.jackhuang.hmcl.launch.ProcessListener;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.java.JavaRuntime;
import org.jackhuang.hmcl.util.platform.ManagedProcess;
import org.jackhuang.hmcl.util.platform.Platform;
@ -31,6 +30,7 @@ import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
@ -45,7 +45,7 @@ public class GameCrashWindowTest {
ManagedProcess process = new ManagedProcess(null, Arrays.asList("commands", "2"));
String logs = FileUtils.readText(new File("../HMCLCore/src/test/resources/logs/too_old_java.txt"));
String logs = Files.readString(new File("../HMCLCore/src/test/resources/logs/too_old_java.txt").toPath());
CountDownLatch latch = new CountDownLatch(1);
FXUtils.runInFX(() -> {

View File

@ -63,8 +63,9 @@ public class DefaultCacheRepository extends CacheRepository {
lock.writeLock().lock();
try {
if (Files.isRegularFile(indexFile))
index = JsonUtils.fromNonNullJson(FileUtils.readText(indexFile), Index.class);
if (Files.isRegularFile(indexFile)) {
index = JsonUtils.fromNonNullJson(Files.readString(indexFile), Index.class);
}
else
index = new Index();
} catch (IOException | JsonParseException e) {

View File

@ -23,7 +23,6 @@ import org.jackhuang.hmcl.task.FileDownloadTask;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.CompressingUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import java.io.IOException;
@ -126,7 +125,7 @@ public final class ForgeInstallTask extends Task<Version> {
Optional<String> gameVersion = dependencyManager.getGameRepository().getGameVersion(version);
if (!gameVersion.isPresent()) throw new IOException();
try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) {
String installProfileText = FileUtils.readText(fs.getPath("install_profile.json"));
String installProfileText = Files.readString(fs.getPath("install_profile.json"));
Map<?, ?> installProfile = JsonUtils.fromNonNullJson(installProfileText, Map.class);
if (installProfile.containsKey("spec")) {
ForgeNewInstallProfile profile = JsonUtils.fromNonNullJson(installProfileText, ForgeNewInstallProfile.class);
@ -159,7 +158,7 @@ public final class ForgeInstallTask extends Task<Version> {
Optional<String> gameVersion = dependencyManager.getGameRepository().getGameVersion(version);
if (!gameVersion.isPresent()) throw new IOException();
try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) {
String installProfileText = FileUtils.readText(fs.getPath("install_profile.json"));
String installProfileText = Files.readString(fs.getPath("install_profile.json"));
Map<?, ?> installProfile = JsonUtils.fromNonNullJson(installProfileText, Map.class);
if (installProfile.containsKey("spec")) {
ForgeNewInstallProfile profile = JsonUtils.fromNonNullJson(installProfileText, ForgeNewInstallProfile.class);

View File

@ -278,9 +278,9 @@ public class ForgeNewInstallTask extends Task<Version> {
@Override
public void preExecute() throws Exception {
try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) {
profile = JsonUtils.fromNonNullJson(FileUtils.readText(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class);
profile = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class);
processors = profile.getProcessors();
forgeVersion = JsonUtils.fromNonNullJson(FileUtils.readText(fs.getPath(profile.getJson())), Version.class);
forgeVersion = JsonUtils.fromNonNullJson(Files.readString(fs.getPath(profile.getJson())), Version.class);
for (Library library : profile.getLibraries()) {
Path file = fs.getPath("maven").resolve(library.getPath());

View File

@ -27,7 +27,6 @@ import org.jackhuang.hmcl.task.FileDownloadTask;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.CacheRepository;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.net.URL;
@ -84,7 +83,7 @@ public final class GameAssetDownloadTask extends Task<Void> {
public void execute() throws Exception {
AssetIndex index;
try {
index = JsonUtils.fromNonNullJson(FileUtils.readText(assetIndexFile), AssetIndex.class);
index = JsonUtils.fromNonNullJson(Files.readString(assetIndexFile), AssetIndex.class);
} catch (IOException | JsonParseException e) {
throw new GameAssetIndexDownloadTask.GameAssetIndexMalformedException();
}

View File

@ -27,7 +27,6 @@ import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.DigestUtils;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.nio.file.Files;
@ -86,7 +85,7 @@ public final class GameAssetIndexDownloadTask extends Task<Void> {
}
} else {
try {
JsonUtils.fromNonNullJson(FileUtils.readText(assetIndexFile), AssetIndex.class);
JsonUtils.fromNonNullJson(Files.readString(assetIndexFile), AssetIndex.class);
return;
} catch (IOException | JsonParseException ignore) {
}

View File

@ -9,7 +9,6 @@ import org.jackhuang.hmcl.task.FileDownloadTask;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.CompressingUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.nio.file.FileSystem;
@ -87,7 +86,7 @@ public final class NeoForgeInstallTask extends Task<Version> {
Optional<String> gameVersion = dependencyManager.getGameRepository().getGameVersion(version);
if (!gameVersion.isPresent()) throw new IOException();
try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) {
String installProfileText = FileUtils.readText(fs.getPath("install_profile.json"));
String installProfileText = Files.readString(fs.getPath("install_profile.json"));
Map<?, ?> installProfile = JsonUtils.fromNonNullJson(installProfileText, Map.class);
if (LibraryAnalyzer.LibraryType.FORGE.getPatchId().equals(installProfile.get("profile")) && (Files.exists(fs.getPath("META-INF/NEOFORGE.RSA")) || installProfileText.contains("neoforge"))) {
ForgeNewInstallProfile profile = JsonUtils.fromNonNullJson(installProfileText, ForgeNewInstallProfile.class);

View File

@ -274,9 +274,9 @@ public class NeoForgeOldInstallTask extends Task<Version> {
@Override
public void preExecute() throws Exception {
try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) {
profile = JsonUtils.fromNonNullJson(FileUtils.readText(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class);
profile = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class);
processors = profile.getProcessors();
neoForgeVersion = JsonUtils.fromNonNullJson(FileUtils.readText(fs.getPath(profile.getJson())), Version.class);
neoForgeVersion = JsonUtils.fromNonNullJson(Files.readString(fs.getPath(profile.getJson())), Version.class);
for (Library library : profile.getLibraries()) {
Path file = fs.getPath("maven").resolve(library.getPath());

View File

@ -175,7 +175,7 @@ public final class OptiFineInstallTask extends Task<Version> {
Path launchWrapperVersionText = fs.getPath("launchwrapper-of.txt");
if (Files.exists(launchWrapperVersionText)) {
String launchWrapperVersion = FileUtils.readText(launchWrapperVersionText).trim();
String launchWrapperVersion = Files.readString(launchWrapperVersionText).trim();
Path launchWrapperJar = fs.getPath("launchwrapper-of-" + launchWrapperVersion + ".jar");
Library launchWrapper = new Library(new Artifact("optifine", "launchwrapper-of", launchWrapperVersion));
@ -192,7 +192,7 @@ public final class OptiFineInstallTask extends Task<Version> {
Path buildofText = fs.getPath("buildof.txt");
if (Files.exists(buildofText)) {
String buildof = FileUtils.readText(buildofText).trim();
String buildof = Files.readString(buildofText).trim();
VersionNumber buildofVer = VersionNumber.asVersion(buildof);
if (LibraryAnalyzer.BOOTSTRAP_LAUNCHER_MAIN.equals(originalMainClass)) {

View File

@ -18,10 +18,10 @@
package org.jackhuang.hmcl.game;
import org.intellij.lang.annotations.Language;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.util.*;
@ -226,7 +226,7 @@ public final class CrashReportAnalyzer {
public static String findCrashReport(String log) throws IOException, InvalidPathException {
Matcher matcher = CRASH_REPORT_LOCATION_PATTERN.matcher(log);
if (matcher.find()) {
return FileUtils.readText(Paths.get(matcher.group("location")));
return Files.readString(Paths.get(matcher.group("location")));
} else {
return null;
}

View File

@ -166,7 +166,7 @@ public class DefaultGameRepository implements GameRepository {
}
public Version readVersionJson(File file) throws IOException, JsonParseException {
String jsonText = FileUtils.readText(file);
String jsonText = Files.readString(file.toPath());
try {
// Try TLauncher version json format
return JsonUtils.fromNonNullJson(jsonText, TLauncherVersion.class).toVersion();
@ -214,7 +214,7 @@ public class DefaultGameRepository implements GameRepository {
if (fromVersion.getId().equals(fromVersion.getJar()))
fromVersion = fromVersion.setJar(null);
FileUtils.writeText(toJson.toFile(), JsonUtils.GSON.toJson(fromVersion.setId(to)));
FileUtils.writeText(toJson, JsonUtils.GSON.toJson(fromVersion.setId(to)));
// fix inheritsFrom of versions that inherits from version [from].
for (Version version : getVersions()) {
@ -384,7 +384,7 @@ public class DefaultGameRepository implements GameRepository {
@Override
public AssetIndex getAssetIndex(String version, String assetId) throws IOException {
try {
return Objects.requireNonNull(JsonUtils.GSON.fromJson(FileUtils.readText(getIndexFile(version, assetId)), AssetIndex.class));
return Objects.requireNonNull(JsonUtils.GSON.fromJson(Files.readString(getIndexFile(version, assetId)), AssetIndex.class));
} catch (JsonParseException | NullPointerException e) {
throw new IOException("Asset index file malformed", e);
}
@ -445,7 +445,7 @@ public class DefaultGameRepository implements GameRepository {
if (!Files.isRegularFile(indexFile))
return assetsDir;
String assetIndexContent = FileUtils.readText(indexFile);
String assetIndexContent = Files.readString(indexFile);
AssetIndex index = JsonUtils.GSON.fromJson(assetIndexContent, AssetIndex.class);
if (index == null)
@ -512,7 +512,7 @@ public class DefaultGameRepository implements GameRepository {
if (!hasVersion(version)) throw new VersionNotFoundException(version);
File file = getModpackConfiguration(version);
if (!file.exists()) return null;
return JsonUtils.GSON.fromJson(FileUtils.readText(file), ModpackConfiguration.class);
return JsonUtils.GSON.fromJson(Files.readString(file.toPath()), ModpackConfiguration.class);
}
public boolean isModpack(String version) {

View File

@ -130,7 +130,7 @@ public class Datapack {
} else if (Files.exists(mcmeta)) { // single datapack
isMultiple = false;
try {
PackMcMeta pack = JsonUtils.fromNonNullJson(FileUtils.readText(mcmeta), PackMcMeta.class);
PackMcMeta pack = JsonUtils.fromNonNullJson(Files.readString(mcmeta), PackMcMeta.class);
Platform.runLater(() -> info.add(new Pack(path, FileUtils.getNameWithoutExtension(path), pack.getPackInfo().getDescription(), this)));
} catch (IOException | JsonParseException e) {
LOG.warning("Failed to read datapack " + path, e);
@ -165,8 +165,8 @@ public class Datapack {
boolean enabled = Files.exists(mcmeta);
try {
PackMcMeta pack = enabled ? JsonUtils.fromNonNullJson(FileUtils.readText(mcmeta), PackMcMeta.class)
: JsonUtils.fromNonNullJson(FileUtils.readText(mcmetaDisabled), PackMcMeta.class);
PackMcMeta pack = enabled ? JsonUtils.fromNonNullJson(Files.readString(mcmeta), PackMcMeta.class)
: JsonUtils.fromNonNullJson(Files.readString(mcmetaDisabled), PackMcMeta.class);
info.add(new Pack(enabled ? mcmeta : mcmetaDisabled, FileUtils.getName(subDir), pack.getPackInfo().getDescription(), this));
} catch (IOException | JsonParseException e) {
LOG.warning("Failed to read datapack " + subDir, e);
@ -186,7 +186,7 @@ public class Datapack {
continue;
name = StringUtils.substringBeforeLast(name, ".zip");
PackMcMeta pack = JsonUtils.fromNonNullJson(FileUtils.readText(mcmeta), PackMcMeta.class);
PackMcMeta pack = JsonUtils.fromNonNullJson(Files.readString(mcmeta), PackMcMeta.class);
info.add(new Pack(subDir, name, pack.getPackInfo().getDescription(), this));
} catch (IOException | JsonParseException e) {
LOG.warning("Failed to read datapack " + subDir, e);

View File

@ -32,6 +32,7 @@ import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
@ -87,7 +88,7 @@ public final class CurseCompletionTask extends Task<Void> {
try {
File manifestFile = new File(repository.getVersionRoot(version), "manifest.json");
if (manifestFile.exists())
this.manifest = JsonUtils.GSON.fromJson(FileUtils.readText(manifestFile), CurseManifest.class);
this.manifest = JsonUtils.GSON.fromJson(Files.readString(manifestFile.toPath()), CurseManifest.class);
} catch (Exception e) {
LOG.warning("Unable to read CurseForge modpack manifest.json", e);
}

View File

@ -29,6 +29,7 @@ import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@ -98,7 +99,7 @@ public final class CurseInstallTask extends Task<Void> {
ModpackConfiguration<CurseManifest> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(CurseManifest.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(CurseManifest.class));
if (!CurseModpackProvider.INSTANCE.getName().equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a Curse modpack. Cannot update this version.");

View File

@ -87,7 +87,7 @@ public class McbbsModpackCompletionTask extends CompletableFutureTask<Void> {
if (configuration == null) {
// Load configuration from disk
try {
configuration = JsonUtils.fromNonNullJson(FileUtils.readText(configurationFile), ModpackConfiguration.typeOf(McbbsModpackManifest.class));
configuration = JsonUtils.fromNonNullJson(Files.readString(configurationFile.toPath()), ModpackConfiguration.typeOf(McbbsModpackManifest.class));
} catch (IOException | JsonParseException e) {
throw new IOException("Malformed modpack configuration");
}

View File

@ -28,10 +28,10 @@ import org.jackhuang.hmcl.mod.ModpackConfiguration;
import org.jackhuang.hmcl.mod.ModpackInstallTask;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -79,7 +79,7 @@ public class McbbsModpackLocalInstallTask extends Task<Void> {
ModpackConfiguration<McbbsModpackManifest> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(McbbsModpackManifest.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(McbbsModpackManifest.class));
if (!McbbsModpackProvider.INSTANCE.getName().equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a Mcbbs modpack. Cannot update this version.");

View File

@ -24,10 +24,10 @@ import org.jackhuang.hmcl.game.DefaultGameRepository;
import org.jackhuang.hmcl.mod.ModpackConfiguration;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -65,7 +65,7 @@ public class McbbsModpackRemoteInstallTask extends Task<Void> {
ModpackConfiguration<McbbsModpackManifest> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(McbbsModpackManifest.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(McbbsModpackManifest.class));
if (!MODPACK_TYPE.equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a Mcbbs modpack. Cannot update this version.");

View File

@ -24,7 +24,6 @@ import org.jackhuang.hmcl.mod.ModLoaderType;
import org.jackhuang.hmcl.mod.ModManager;
import org.jackhuang.hmcl.util.Immutable;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.lang.reflect.Type;
@ -64,7 +63,7 @@ public final class FabricModMetadata {
Path mcmod = fs.getPath("fabric.mod.json");
if (Files.notExists(mcmod))
throw new IOException("File " + modFile + " is not a Fabric mod.");
FabricModMetadata metadata = JsonUtils.fromNonNullJson(FileUtils.readText(mcmod), FabricModMetadata.class);
FabricModMetadata metadata = JsonUtils.fromNonNullJson(Files.readString(mcmod), FabricModMetadata.class);
String authors = metadata.authors == null ? "" : metadata.authors.stream().map(author -> author.name).collect(Collectors.joining(", "));
return new LocalModFile(modManager, modManager.getLocalMod(metadata.id, ModLoaderType.FABRIC), modFile, metadata.name, new LocalModFile.Description(metadata.description),
authors, metadata.version, "", metadata.contact != null ? metadata.contact.getOrDefault("homepage", "") : "", metadata.icon);

View File

@ -6,7 +6,6 @@ import org.jackhuang.hmcl.mod.LocalModFile;
import org.jackhuang.hmcl.mod.ModLoaderType;
import org.jackhuang.hmcl.mod.ModManager;
import org.jackhuang.hmcl.util.Immutable;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.io.InputStream;
@ -134,7 +133,7 @@ public final class ForgeNewModMetadata {
Path modToml = fs.getPath(tomlPath);
if (Files.notExists(modToml))
throw new IOException("File " + modFile + " is not a Forge 1.13+ or NeoForge mod.");
Toml toml = new Toml().read(FileUtils.readText(modToml));
Toml toml = new Toml().read(Files.readString(modToml));
ForgeNewModMetadata metadata = toml.to(ForgeNewModMetadata.class);
if (metadata == null || metadata.getMods().isEmpty())
throw new IOException("Mod " + modFile + " `mods.toml` is malformed..");

View File

@ -25,7 +25,6 @@ import org.jackhuang.hmcl.mod.ModManager;
import org.jackhuang.hmcl.util.Immutable;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.nio.file.FileSystem;
@ -126,7 +125,7 @@ public final class ForgeOldModMetadata {
Path mcmod = fs.getPath("mcmod.info");
if (Files.notExists(mcmod))
throw new IOException("File " + modFile + " is not a Forge mod.");
List<ForgeOldModMetadata> modList = JsonUtils.GSON.fromJson(FileUtils.readText(mcmod), listTypeOf(ForgeOldModMetadata.class));
List<ForgeOldModMetadata> modList = JsonUtils.GSON.fromJson(Files.readString(mcmod), listTypeOf(ForgeOldModMetadata.class));
if (modList == null || modList.isEmpty())
throw new IOException("Mod " + modFile + " `mcmod.info` is malformed..");
ForgeOldModMetadata metadata = modList.get(0);

View File

@ -148,7 +148,7 @@ public class PackMcMeta implements Validation {
Path mcmod = fs.getPath("pack.mcmeta");
if (Files.notExists(mcmod))
throw new IOException("File " + modFile + " is not a resource pack.");
PackMcMeta metadata = JsonUtils.fromNonNullJson(FileUtils.readText(mcmod), PackMcMeta.class);
PackMcMeta metadata = JsonUtils.fromNonNullJson(Files.readString(mcmod), PackMcMeta.class);
return new LocalModFile(
modManager,
modManager.getLocalMod(FileUtils.getNameWithoutExtension(modFile), ModLoaderType.PACK),

View File

@ -7,7 +7,6 @@ import org.jackhuang.hmcl.mod.ModLoaderType;
import org.jackhuang.hmcl.mod.ModManager;
import org.jackhuang.hmcl.util.Immutable;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.IOException;
import java.nio.file.FileSystem;
@ -60,7 +59,7 @@ public final class QuiltModMetadata {
throw new IOException("File " + modFile + " is not a Quilt mod.");
}
QuiltModMetadata root = JsonUtils.fromNonNullJson(FileUtils.readText(path), QuiltModMetadata.class);
QuiltModMetadata root = JsonUtils.fromNonNullJson(Files.readString(path), QuiltModMetadata.class);
if (root.schema_version != 1) {
throw new IOException("File " + modFile + " is not a supported Quilt mod.");
}

View File

@ -80,7 +80,7 @@ public class ModrinthCompletionTask extends Task<Void> {
try {
File manifestFile = new File(repository.getVersionRoot(version), "modrinth.index.json");
if (manifestFile.exists())
this.manifest = JsonUtils.GSON.fromJson(FileUtils.readText(manifestFile), ModrinthManifest.class);
this.manifest = JsonUtils.GSON.fromJson(Files.readString(manifestFile.toPath()), ModrinthManifest.class);
} catch (Exception e) {
LOG.warning("Unable to read Modrinth modpack manifest.json", e);
}

View File

@ -93,7 +93,7 @@ public class ModrinthInstallTask extends Task<Void> {
ModpackConfiguration<ModrinthManifest> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(ModrinthManifest.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(ModrinthManifest.class));
if (!ModrinthModpackProvider.INSTANCE.getName().equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a Modrinth modpack. Cannot update this version.");

View File

@ -38,7 +38,6 @@ import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
@ -111,7 +110,7 @@ public final class MultiMCModpackInstallTask extends Task<MultiMCInstancePatch.R
ModpackConfiguration<MultiMCInstanceConfiguration> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(MultiMCInstanceConfiguration.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(MultiMCInstanceConfiguration.class));
if (!MultiMCModpackProvider.INSTANCE.getName().equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a MultiMC modpack. Cannot update this version.");
@ -146,7 +145,7 @@ public final class MultiMCModpackInstallTask extends Task<MultiMCInstancePatch.R
throw new IllegalArgumentException("Json-Patch isn't a file: " + componentID);
}
MultiMCInstancePatch patch = MultiMCInstancePatch.read(componentID, FileUtils.readText(patchPath, StandardCharsets.UTF_8));
MultiMCInstancePatch patch = MultiMCInstancePatch.read(componentID, Files.readString(patchPath));
patches.add(Task.supplyAsync(() -> patch)); // TODO: Task.completed has unclear compatibility issue.
} else {
patches.add(

View File

@ -65,7 +65,7 @@ public class ServerModpackCompletionTask extends Task<Void> {
try {
File manifestFile = repository.getModpackConfiguration(version);
if (manifestFile.exists()) {
this.manifest = JsonUtils.GSON.fromJson(FileUtils.readText(manifestFile), ModpackConfiguration.typeOf(ServerModpackManifest.class));
this.manifest = JsonUtils.GSON.fromJson(Files.readString(manifestFile.toPath()), ModpackConfiguration.typeOf(ServerModpackManifest.class));
}
} catch (Exception e) {
LOG.warning("Unable to read Server modpack manifest.json", e);

View File

@ -27,10 +27,10 @@ import org.jackhuang.hmcl.mod.ModpackConfiguration;
import org.jackhuang.hmcl.mod.ModpackInstallTask;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -71,7 +71,7 @@ public class ServerModpackLocalInstallTask extends Task<Void> {
ModpackConfiguration<ServerModpackManifest> config = null;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(ServerModpackManifest.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(ServerModpackManifest.class));
if (!ServerModpackProvider.INSTANCE.getName().equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a Server modpack. Cannot update this version.");

View File

@ -24,10 +24,10 @@ import org.jackhuang.hmcl.game.DefaultGameRepository;
import org.jackhuang.hmcl.mod.ModpackConfiguration;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -65,7 +65,7 @@ public class ServerModpackRemoteInstallTask extends Task<Void> {
ModpackConfiguration<ServerModpackManifest> config;
try {
if (json.exists()) {
config = JsonUtils.GSON.fromJson(FileUtils.readText(json), ModpackConfiguration.typeOf(ServerModpackManifest.class));
config = JsonUtils.GSON.fromJson(Files.readString(json.toPath()), ModpackConfiguration.typeOf(ServerModpackManifest.class));
if (!MODPACK_TYPE.equals(config.getType()))
throw new IllegalArgumentException("Version " + name + " is not a Server modpack. Cannot update this version.");

View File

@ -17,13 +17,12 @@
*/
package org.jackhuang.hmcl.task;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
@ -67,7 +66,7 @@ public final class GetTask extends FetchTask<String> {
@Override
protected void useCachedResult(Path cachedFile) throws IOException {
setResult(FileUtils.readText(cachedFile));
setResult(Files.readString(cachedFile));
}
@Override
@ -84,7 +83,7 @@ public final class GetTask extends FetchTask<String> {
public void close() throws IOException {
if (!isSuccess()) return;
String result = baos.toString(charset.name());
String result = baos.toString(charset);
setResult(result);
if (checkETag) {

View File

@ -66,7 +66,7 @@ public class CacheRepository {
}
if (Files.isRegularFile(indexFile)) {
ETagIndex raw = GSON.fromJson(FileUtils.readText(indexFile), ETagIndex.class);
ETagIndex raw = GSON.fromJson(Files.readString(indexFile), ETagIndex.class);
if (raw == null)
index = new HashMap<>();
else
@ -410,7 +410,7 @@ public class CacheRepository {
try {
indexFile = cacheDirectory.resolve(name + ".json");
if (Files.isRegularFile(indexFile)) {
joinEntries(fromNonNullJson(FileUtils.readText(indexFile), mapTypeOf(String.class, Object.class)));
joinEntries(fromNonNullJson(Files.readString(indexFile), mapTypeOf(String.class, Object.class)));
}
} catch (IOException | JsonParseException e) {
LOG.warning("Unable to read storage {" + name + "} file");

View File

@ -25,7 +25,6 @@ import org.jackhuang.hmcl.util.function.ExceptionalConsumer;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.ZonedDateTime;
@ -113,22 +112,6 @@ public final class FileUtils {
else return getName(path);
}
public static String readText(File file) throws IOException {
return readText(file, UTF_8);
}
public static String readText(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
}
public static String readText(Path file) throws IOException {
return readText(file, UTF_8);
}
public static String readText(Path file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file), charset);
}
public static String readTextMaybeNativeEncoding(Path file) throws IOException {
byte[] bytes = Files.readAllBytes(file);
@ -159,7 +142,7 @@ public final class FileUtils {
* @throws IOException if an I/O error occurs
*/
public static void writeText(File file, String text) throws IOException {
writeText(file, text, UTF_8);
writeText(file.toPath(), text);
}
/**
@ -174,39 +157,8 @@ public final class FileUtils {
* @throws IOException if an I/O error occurs
*/
public static void writeText(Path file, String text) throws IOException {
writeText(file, text, UTF_8);
}
/**
* Write plain text to file.
* <p>
* We don't care about platform difference of line separator. Because readText accept all possibilities of line separator.
* It will create the file if it does not exist, or truncate the existing file to empty for rewriting.
* All characters in text will be written into the file in binary format. Existing data will be erased.
*
* @param file the path to the file
* @param text the text being written to file
* @param charset the charset to use for encoding
* @throws IOException if an I/O error occurs
*/
public static void writeText(File file, String text, Charset charset) throws IOException {
writeBytes(file, text.getBytes(charset));
}
/**
* Write plain text to file.
* <p>
* We don't care about platform difference of line separator. Because readText accept all possibilities of line separator.
* It will create the file if it does not exist, or truncate the existing file to empty for rewriting.
* All characters in text will be written into the file in binary format. Existing data will be erased.
*
* @param file the path to the file
* @param text the text being written to file
* @param charset the charset to use for encoding
* @throws IOException if an I/O error occurs
*/
public static void writeText(Path file, String text, Charset charset) throws IOException {
writeBytes(file, text.getBytes(charset));
Files.createDirectories(file.getParent());
Files.writeString(file, text);
}
/**

View File

@ -19,7 +19,6 @@ package org.jackhuang.hmcl.util.platform.linux;
import org.jackhuang.hmcl.util.KeyValuePairUtils;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.hardware.CentralProcessor;
import org.jackhuang.hmcl.util.platform.hardware.HardwareVendor;
import org.jetbrains.annotations.Nullable;
@ -119,7 +118,7 @@ final class LinuxCPUDetector {
Path compatiblePath = Paths.get("/proc/device-tree/compatible");
if (Files.isRegularFile(compatiblePath)) {
// device-vendor,device-model\0soc-vendor,soc-model\0
String[] data = FileUtils.readText(compatiblePath).split("\0");
String[] data = Files.readString(compatiblePath).split("\0");
for (int i = data.length - 1; i >= 0; i--) {
String device = data[i];
@ -207,10 +206,10 @@ final class LinuxCPUDetector {
if (!dirNamePattern.matcher(cpuDir.getFileName().toString()).matches() || !Files.isDirectory(cpuDir))
continue;
physicalPackageIds.add(Integer.parseInt(FileUtils.readText(cpuDir.resolve("topology/physical_package_id")).trim()));
physicalPackageIds.add(Integer.parseInt(Files.readString(cpuDir.resolve("topology/physical_package_id")).trim()));
boolean shouldCount = false;
for (String item : FileUtils.readText(cpuDir.resolve("topology/core_cpus_list")).trim().split(",")) {
for (String item : Files.readString(cpuDir.resolve("topology/core_cpus_list")).trim().split(",")) {
String range = item.trim();
int idx = range.indexOf('-');
if (idx < 0)

View File

@ -22,7 +22,6 @@ import org.glavo.pci.ids.model.Device;
import org.glavo.pci.ids.model.Vendor;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.hardware.GraphicsCard;
import org.jackhuang.hmcl.util.platform.hardware.HardwareVendor;
@ -97,11 +96,11 @@ final class LinuxGPUDetector {
Path versionFile = deviceDir.resolve("driver/module/version");
if (Files.isRegularFile(versionFile)) {
builder.setDriverVersion(FileUtils.readText(versionFile).trim());
builder.setDriverVersion(Files.readString(versionFile).trim());
} else if ("zx".equals(name)) {
versionFile = deviceDir.resolve("zx_info/driver_version");
if (Files.isRegularFile(versionFile)) {
builder.setDriverVersion(FileUtils.readText(versionFile).trim());
builder.setDriverVersion(Files.readString(versionFile).trim());
}
}
}
@ -158,7 +157,7 @@ final class LinuxGPUDetector {
Path revisionFile = deviceDir.resolve("revision");
if (Files.isRegularFile(revisionFile)) {
String revisionString = FileUtils.readText(revisionFile).trim();
String revisionString = Files.readString(revisionFile).trim();
int revision = Integer.decode(revisionString);
String prefix = String.format("%X,\t%X,\t", deviceId, revision);
//noinspection DataFlowIssue
@ -299,7 +298,7 @@ final class LinuxGPUDetector {
continue;
try {
String modalias = FileUtils.readText(modaliasFile).trim();
String modalias = Files.readString(modaliasFile).trim();
GraphicsCard graphicsCard = null;
if (modalias.startsWith("pci:"))
graphicsCard = detectPCI(deviceDir, modalias);