Close #2987: 从 java.io.File 迁移至 NIO (#4502)

This commit is contained in:
Glavo 2025-09-17 21:41:17 +08:00 committed by GitHub
parent 77fadf5d28
commit 45f7719096
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 53 additions and 131 deletions

View File

@ -26,7 +26,6 @@ import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.ManagedProcess;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
@ -141,7 +140,7 @@ public final class HMCLGameLauncher extends DefaultLauncher {
}
@Override
public void makeLaunchScript(File scriptFile) throws IOException {
public void makeLaunchScript(Path scriptFile) throws IOException {
generateOptionsTxt();
super.makeLaunchScript(scriptFile);
}

View File

@ -49,7 +49,6 @@ import org.jackhuang.hmcl.util.platform.*;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import org.jackhuang.hmcl.util.versioning.VersionNumber;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketTimeoutException;
@ -77,7 +76,7 @@ public final class LauncherHelper {
private final Profile profile;
private Account account;
private final String selectedVersion;
private File scriptFile;
private Path scriptFile;
private final VersionSetting setting;
private LauncherVisibility launcherVisibility;
private boolean showLogs;
@ -120,9 +119,8 @@ public final class LauncherHelper {
launch0();
}
public void makeLaunchScript(File scriptFile) {
public void makeLaunchScript(Path scriptFile) {
this.scriptFile = Objects.requireNonNull(scriptFile);
launch();
}
@ -151,7 +149,7 @@ public final class LauncherHelper {
dependencyManager.checkGameCompletionAsync(version.get(), integrityCheck),
Task.composeAsync(() -> {
try {
ModpackConfiguration<?> configuration = ModpackHelper.readModpackConfiguration(repository.getModpackConfiguration(selectedVersion).toFile());
ModpackConfiguration<?> configuration = ModpackHelper.readModpackConfiguration(repository.getModpackConfiguration(selectedVersion));
ModpackProvider provider = ModpackHelper.getProviderByType(configuration.getType());
if (provider == null) return null;
else return provider.createCompletionTask(dependencyManager, selectedVersion);
@ -225,7 +223,7 @@ public final class LauncherHelper {
} else {
runLater(() -> {
launchingStepsPane.fireEvent(new DialogCloseEvent());
Controllers.dialog(i18n("version.launch_script.success", scriptFile.getAbsolutePath()));
Controllers.dialog(i18n("version.launch_script.success", FileUtils.getAbsolutePath(scriptFile)));
});
}
}).withFakeProgress(

View File

@ -44,7 +44,6 @@ import org.jackhuang.hmcl.util.io.CompressingUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
@ -60,7 +59,8 @@ import static org.jackhuang.hmcl.util.Lang.toIterable;
import static org.jackhuang.hmcl.util.Pair.pair;
public final class ModpackHelper {
private ModpackHelper() {}
private ModpackHelper() {
}
private static final Map<String, ModpackProvider> providers = mapOf(
pair(CurseModpackProvider.INSTANCE.getName(), CurseModpackProvider.INSTANCE),
@ -138,15 +138,12 @@ public final class ModpackHelper {
(path.getFileName() == null || ".minecraft".equals(FileUtils.getName(path)));
}
public static ModpackConfiguration<?> readModpackConfiguration(File file) throws IOException {
if (!file.exists())
throw new FileNotFoundException(file.getPath());
else
try {
return JsonUtils.fromJsonFile(file.toPath(), ModpackConfiguration.class);
} catch (JsonParseException e) {
throw new IOException("Malformed modpack configuration");
}
public static ModpackConfiguration<?> readModpackConfiguration(Path file) throws IOException {
try {
return JsonUtils.fromJsonFile(file, ModpackConfiguration.class);
} catch (JsonParseException e) {
throw new IOException("Malformed modpack configuration");
}
}
public static Task<?> getInstallTask(Profile profile, ServerModpackManifest manifest, String name, Modpack modpack) {
@ -177,12 +174,12 @@ public final class ModpackHelper {
return Files.exists(Paths.get("externalgames").resolve(name));
}
public static Task<?> getInstallManuallyCreatedModpackTask(Profile profile, File zipFile, String name, Charset charset) {
public static Task<?> getInstallManuallyCreatedModpackTask(Profile profile, Path zipFile, String name, Charset charset) {
if (isExternalGameNameConflicts(name)) {
throw new IllegalArgumentException("name existing");
}
return new ManuallyCreatedModpackInstallTask(profile, zipFile.toPath(), charset, name)
return new ManuallyCreatedModpackInstallTask(profile, zipFile, charset, name)
.thenAcceptAsync(Schedulers.javafx(), location -> {
Profile newProfile = new Profile(name, location);
newProfile.setUseRelativePath(true);
@ -191,7 +188,7 @@ public final class ModpackHelper {
});
}
public static Task<?> getInstallTask(Profile profile, File zipFile, String name, Modpack modpack) {
public static Task<?> getInstallTask(Profile profile, Path zipFile, String name, Modpack modpack) {
profile.getRepository().markVersionAsModpack(name);
ExceptionalRunnable<?> success = () -> {
@ -211,17 +208,17 @@ public final class ModpackHelper {
};
if (modpack.getManifest() instanceof MultiMCInstanceConfiguration)
return modpack.getInstallTask(profile.getDependency(), zipFile.toPath(), name)
return modpack.getInstallTask(profile.getDependency(), zipFile, name)
.whenComplete(Schedulers.defaultScheduler(), success, failure)
.thenComposeAsync(createMultiMCPostInstallTask(profile, (MultiMCInstanceConfiguration) modpack.getManifest(), name))
.withStagesHint(List.of("hmcl.modpack", "hmcl.modpack.download"));
else if (modpack.getManifest() instanceof McbbsModpackManifest)
return modpack.getInstallTask(profile.getDependency(), zipFile.toPath(), name)
return modpack.getInstallTask(profile.getDependency(), zipFile, name)
.whenComplete(Schedulers.defaultScheduler(), success, failure)
.thenComposeAsync(createMcbbsPostInstallTask(profile, (McbbsModpackManifest) modpack.getManifest(), name))
.withStagesHint(List.of("hmcl.modpack", "hmcl.modpack.download"));
else
return modpack.getInstallTask(profile.getDependency(), zipFile.toPath(), name)
return modpack.getInstallTask(profile.getDependency(), zipFile, name)
.whenComplete(Schedulers.javafx(), success, failure)
.withStagesHint(List.of("hmcl.modpack", "hmcl.modpack.download"));
}
@ -236,17 +233,17 @@ public final class ModpackHelper {
}
}
public static Task<?> getUpdateTask(Profile profile, File zipFile, Charset charset, String name, ModpackConfiguration<?> configuration) throws UnsupportedModpackException, ManuallyCreatedModpackException, MismatchedModpackTypeException {
Modpack modpack = ModpackHelper.readModpackManifest(zipFile.toPath(), charset);
public static Task<?> getUpdateTask(Profile profile, Path zipFile, Charset charset, String name, ModpackConfiguration<?> configuration) throws UnsupportedModpackException, ManuallyCreatedModpackException, MismatchedModpackTypeException {
Modpack modpack = ModpackHelper.readModpackManifest(zipFile, charset);
ModpackProvider provider = getProviderByType(configuration.getType());
if (provider == null) {
throw new UnsupportedModpackException();
}
if (modpack.getManifest() instanceof MultiMCInstanceConfiguration)
return provider.createUpdateTask(profile.getDependency(), name, zipFile.toPath(), modpack)
return provider.createUpdateTask(profile.getDependency(), name, zipFile, modpack)
.thenComposeAsync(() -> createMultiMCPostUpdateTask(profile, (MultiMCInstanceConfiguration) modpack.getManifest(), name));
else
return provider.createUpdateTask(profile.getDependency(), name, zipFile.toPath(), modpack);
return provider.createUpdateTask(profile.getDependency(), name, zipFile, modpack);
}
public static void toVersionSetting(MultiMCInstanceConfiguration c, VersionSetting vs) {

View File

@ -41,7 +41,6 @@ import org.jackhuang.hmcl.util.javafx.DirtyTracker;
import org.jackhuang.hmcl.util.javafx.ObservableHelper;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.*;
import java.net.Proxy;
@ -55,7 +54,6 @@ public final class Config implements Observable {
public static final int CURRENT_UI_VERSION = 0;
public static final Gson CONFIG_GSON = new GsonBuilder()
.registerTypeAdapter(File.class, FileTypeAdapter.INSTANCE)
.registerTypeAdapter(Path.class, PathTypeAdapter.INSTANCE)
.registerTypeAdapter(ObservableList.class, new ObservableListCreator())
.registerTypeAdapter(ObservableSet.class, new ObservableSetCreator())

View File

@ -32,7 +32,6 @@ import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.ui.construct.MessageDialogPane.MessageType;
import org.jackhuang.hmcl.ui.wizard.WizardController;
import org.jackhuang.hmcl.ui.wizard.WizardProvider;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -84,7 +83,7 @@ public final class ModpackInstallWizardProvider implements WizardProvider {
boolean isManuallyCreated = tryCast(settings.get(LocalModpackPage.MODPACK_MANUALLY_CREATED), Boolean.class).orElse(false);
if (isManuallyCreated) {
return ModpackHelper.getInstallManuallyCreatedModpackTask(profile, FileUtils.toFile(selected), name, charset);
return ModpackHelper.getInstallManuallyCreatedModpackTask(profile, selected, name, charset);
}
if ((selected == null && serverModpackManifest == null) || modpack == null || name == null) return null;
@ -96,9 +95,9 @@ public final class ModpackInstallWizardProvider implements WizardProvider {
}
try {
if (serverModpackManifest != null) {
return ModpackHelper.getUpdateTask(profile, serverModpackManifest, modpack.getEncoding(), name, ModpackHelper.readModpackConfiguration(profile.getRepository().getModpackConfiguration(name).toFile()));
return ModpackHelper.getUpdateTask(profile, serverModpackManifest, modpack.getEncoding(), name, ModpackHelper.readModpackConfiguration(profile.getRepository().getModpackConfiguration(name)));
} else {
return ModpackHelper.getUpdateTask(profile, selected.toFile(), modpack.getEncoding(), name, ModpackHelper.readModpackConfiguration(profile.getRepository().getModpackConfiguration(name).toFile()));
return ModpackHelper.getUpdateTask(profile, selected, modpack.getEncoding(), name, ModpackHelper.readModpackConfiguration(profile.getRepository().getModpackConfiguration(name)));
}
} catch (UnsupportedModpackException | ManuallyCreatedModpackException e) {
Controllers.dialog(i18n("modpack.unsupported"), i18n("message.error"), MessageType.ERROR);
@ -113,7 +112,7 @@ public final class ModpackInstallWizardProvider implements WizardProvider {
return ModpackHelper.getInstallTask(profile, serverModpackManifest, name, modpack)
.thenRunAsync(Schedulers.javafx(), () -> profile.setSelectedVersion(name));
} else {
return ModpackHelper.getInstallTask(profile, selected.toFile(), name, modpack)
return ModpackHelper.getInstallTask(profile, selected, name, modpack)
.thenRunAsync(Schedulers.javafx(), () -> profile.setSelectedVersion(name));
}
}

View File

@ -218,7 +218,7 @@ public class RootPage extends DecoratorAnimatedPage implements DecoratorPage {
.thenApplyAsync(
encoding -> ModpackHelper.readModpackManifest(modpackFile, encoding))
.thenApplyAsync(modpack -> ModpackHelper
.getInstallTask(repository.getProfile(), modpackFile.toFile(), modpack.getName(), modpack)
.getInstallTask(repository.getProfile(), modpackFile, modpack.getName(), modpack)
.executor())
.thenAcceptAsync(Schedulers.javafx(), executor -> {
Controllers.taskDialog(executor, i18n("modpack.installing"), TaskCancellationAction.NO_CANCEL);

View File

@ -201,7 +201,7 @@ public final class Versions {
chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(i18n("extension.ps1"), "*.ps1"));
Path file = FileUtils.toPath(chooser.showSaveDialog(Controllers.getStage()));
if (file != null)
new LauncherHelper(profile, account, id).makeLaunchScript(file.toFile());
new LauncherHelper(profile, account, id).makeLaunchScript(file);
});
}

View File

@ -30,8 +30,6 @@ import org.jackhuang.hmcl.util.io.ChecksumMismatchException;
import org.jackhuang.hmcl.util.platform.UnsupportedPlatformException;
import org.tukaani.xz.LZMAInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@ -102,17 +100,22 @@ public final class MojangJavaDownloadTask extends Task<MojangJavaDownloadTask.Re
if (file.getDownloads().containsKey("lzma")) {
DownloadInfo download = file.getDownloads().get("lzma");
File tempFile = target.resolve(entry.getKey() + ".lzma").toFile();
var task = new FileDownloadTask(downloadProvider.injectURLWithCandidates(download.getUrl()), tempFile.toPath(), new FileDownloadTask.IntegrityCheck("SHA-1", download.getSha1()));
Path tempFile = target.resolve(entry.getKey() + ".lzma");
var task = new FileDownloadTask(downloadProvider.injectURLWithCandidates(download.getUrl()), tempFile, new FileDownloadTask.IntegrityCheck("SHA-1", download.getSha1()));
task.setName(entry.getKey());
dependencies.add(task.thenRunAsync(() -> {
Path decompressed = target.resolve(entry.getKey() + ".tmp");
try (LZMAInputStream input = new LZMAInputStream(new FileInputStream(tempFile))) {
try (LZMAInputStream input = new LZMAInputStream(Files.newInputStream(tempFile))) {
Files.copy(input, decompressed, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new ArtifactMalformedException("File " + entry.getKey() + " is malformed", e);
}
tempFile.delete();
try {
Files.deleteIfExists(tempFile);
} catch (IOException e) {
LOG.warning("Failed to delete temporary file: " + tempFile, e);
}
Files.move(decompressed, dest, StandardCopyOption.REPLACE_EXISTING);
if (file.isExecutable()) {

View File

@ -19,7 +19,7 @@ package org.jackhuang.hmcl.event;
import org.jackhuang.hmcl.util.ToStringBuilder;
import java.io.File;
import java.nio.file.Path;
/**
* This event gets fired when json of a game version is malformed. You can do something here.
@ -30,7 +30,7 @@ import java.io.File;
*/
public final class GameJsonParseFailedEvent extends Event {
private final String version;
private final File jsonFile;
private final Path jsonFile;
/**
*
@ -38,13 +38,13 @@ public final class GameJsonParseFailedEvent extends Event {
* @param jsonFile the minecraft.json file.
* @param version the version name
*/
public GameJsonParseFailedEvent(Object source, File jsonFile, String version) {
public GameJsonParseFailedEvent(Object source, Path jsonFile, String version) {
super(source);
this.version = version;
this.jsonFile = jsonFile;
}
public File getJsonFile() {
public Path getJsonFile() {
return jsonFile;
}

View File

@ -326,7 +326,7 @@ public class DefaultGameRepository implements GameRepository {
} catch (Exception e) {
LOG.warning("Malformed version json " + id, e);
// JsonSyntaxException or IOException or NullPointerException(!!)
if (EventBus.EVENT_BUS.fireEvent(new GameJsonParseFailedEvent(this, json.toFile(), id)) != Event.Result.ALLOW)
if (EventBus.EVENT_BUS.fireEvent(new GameJsonParseFailedEvent(this, json, id)) != Event.Result.ALLOW)
return Stream.empty();
try {

View File

@ -580,7 +580,7 @@ public class DefaultLauncher extends Launcher {
}
@Override
public void makeLaunchScript(File scriptFile) throws IOException {
public void makeLaunchScript(Path scriptFile) throws IOException {
boolean isWindows = OperatingSystem.WINDOWS == OperatingSystem.CURRENT_OS;
Path nativeFolder;
@ -597,7 +597,7 @@ public class DefaultLauncher extends Launcher {
if (isUsingLog4j())
extractLog4jConfigurationFile();
String scriptExtension = FileUtils.getExtension(scriptFile.getName());
String scriptExtension = FileUtils.getExtension(scriptFile);
boolean usePowerShell = "ps1".equals(scriptExtension);
if (!usePowerShell) {
@ -617,9 +617,9 @@ public class DefaultLauncher extends Launcher {
}
}
Files.createDirectories(scriptFile.toPath().getParent());
Files.createDirectories(scriptFile.getParent());
try (OutputStream outputStream = Files.newOutputStream(scriptFile.toPath())) {
try (OutputStream outputStream = Files.newOutputStream(scriptFile)) {
Charset charset = StandardCharsets.UTF_8;
if (isWindows) {
@ -736,7 +736,7 @@ public class DefaultLauncher extends Launcher {
}
}
}
if (!scriptFile.setExecutable(true))
if (!scriptFile.toFile().setExecutable(true))
throw new PermissionException();
if (usePowerShell && !CommandBuilder.hasExecutionPolicy())

View File

@ -23,8 +23,8 @@ import org.jackhuang.hmcl.game.LaunchOptions;
import org.jackhuang.hmcl.game.Version;
import org.jackhuang.hmcl.util.platform.ManagedProcess;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
*
@ -59,7 +59,7 @@ public abstract class Launcher {
/**
* @param file the file path.
*/
public abstract void makeLaunchScript(File file) throws IOException;
public abstract void makeLaunchScript(Path file) throws IOException;
public abstract ManagedProcess launch() throws IOException, InterruptedException;

View File

@ -1,52 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.util.gson;
import com.google.gson.*;
import java.io.File;
import java.lang.reflect.Type;
/**
*
* @author huangyuhui
*/
public final class FileTypeAdapter implements JsonSerializer<File>, JsonDeserializer<File> {
public static final FileTypeAdapter INSTANCE = new FileTypeAdapter();
private FileTypeAdapter() {
}
@Override
public JsonElement serialize(File t, Type type, JsonSerializationContext jsc) {
if (t == null)
return JsonNull.INSTANCE;
else
return new JsonPrimitive(t.getPath());
}
@Override
public File deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
if (je == null)
return null;
else
return new File(je.getAsString());
}
}

View File

@ -23,7 +23,6 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@ -150,7 +149,6 @@ public final class JsonUtils {
.setPrettyPrinting()
.registerTypeAdapter(Instant.class, InstantTypeAdapter.INSTANCE)
.registerTypeAdapter(UUID.class, UUIDTypeAdapter.INSTANCE)
.registerTypeAdapter(File.class, FileTypeAdapter.INSTANCE)
.registerTypeAdapter(Path.class, PathTypeAdapter.INSTANCE)
.registerTypeAdapterFactory(ValidationTypeAdapterFactory.INSTANCE)
.registerTypeAdapterFactory(LowerCaseEnumTypeAdapterFactory.INSTANCE)

View File

@ -61,14 +61,6 @@ public final class FileUtils {
return files.stream().map(FileUtils::toPath).filter(Objects::nonNull).toList();
}
public static @Nullable File toFile(@Nullable Path file) {
try {
return file != null ? file.toFile() : null;
} catch (UnsupportedOperationException ignored) {
return null;
}
}
public static boolean canCreateDirectory(String path) {
try {
return canCreateDirectory(Paths.get(path));

View File

@ -17,7 +17,6 @@
*/
package org.jackhuang.hmcl.util.io;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@ -43,16 +42,6 @@ public final class Unzipper {
this.dest = destDir;
}
/**
* Decompress the given zip file to a directory.
*
* @param zipFile the input zip file to be uncompressed
* @param destDir the dest directory to hold uncompressed files
*/
public Unzipper(File zipFile, File destDir) {
this(zipFile.toPath(), destDir.toPath());
}
/**
* True if replace the existent files in destination directory,
* otherwise those conflict files will be ignored.

View File

@ -20,7 +20,8 @@ package org.jackhuang.hmcl.util.platform;
import org.jackhuang.hmcl.util.io.IOUtils;
import org.jackhuang.hmcl.util.versioning.VersionNumber;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
@ -218,7 +219,7 @@ public enum Architecture {
"/bin/uname",
"/usr/bin/uname"
}) {
if (new File(uname).exists()) {
if (Files.exists(Path.of(uname))) {
try {
Process process = Runtime.getRuntime().exec(new String[]{uname, "-m"});
if (process.waitFor(3, TimeUnit.SECONDS) && process.exitValue() == 0) {