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
17 changed files with 53 additions and 131 deletions

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) {