使用 readAllBytes 和 transferTo 简化代码 (#4115)

This commit is contained in:
Glavo 2025-07-26 19:49:05 +08:00 committed by GitHub
parent fe3fc0413c
commit 43b769923b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 17 additions and 58 deletions

View File

@ -64,7 +64,7 @@ final class ExecutableHeaderHelper {
ZipEntry entry = zip.getEntry(location);
if (entry != null && !entry.isDirectory()) {
try (InputStream in = zip.getInputStream(entry)) {
return Optional.of(IOUtils.readFullyAsByteArray(in));
return Optional.of(IOUtils.readFully(in));
}
}
}

View File

@ -55,7 +55,7 @@ public final class IntegrityChecker {
if (in == null) {
throw new IOException("Public key not found");
}
return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(IOUtils.readFullyAsByteArray(in)));
return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(IOUtils.readFully(in)));
} catch (GeneralSecurityException e) {
throw new IOException("Failed to load public key", e);
}
@ -76,7 +76,7 @@ public final class IntegrityChecker {
}
if (SIGNATURE_FILE.equals(filename)) {
signature = IOUtils.readFullyAsByteArray(in);
signature = IOUtils.readFully(in);
} else {
md.reset();
fileFingerprints.put(filename, DigestUtils.digest(md, in));

View File

@ -17,6 +17,7 @@
*/
package org.jackhuang.hmcl.auth.authlibinjector;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyMap;
import static org.jackhuang.hmcl.util.Lang.tryCast;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
@ -32,7 +33,6 @@ import java.util.Optional;
import org.jackhuang.hmcl.auth.yggdrasil.YggdrasilService;
import org.jackhuang.hmcl.util.io.HttpRequest;
import org.jackhuang.hmcl.util.io.IOUtils;
import org.jackhuang.hmcl.util.javafx.ObservableHelper;
import org.jetbrains.annotations.Nullable;
@ -77,7 +77,7 @@ public class AuthlibInjectorServer implements Observable {
try {
AuthlibInjectorServer server = new AuthlibInjectorServer(url);
server.refreshMetadata(IOUtils.readFullyAsStringWithClosing(conn.getInputStream()));
server.refreshMetadata(new String(conn.getInputStream().readAllBytes(), UTF_8));
return server;
} finally {
conn.disconnect();

View File

@ -25,7 +25,6 @@ import org.jackhuang.hmcl.game.Version;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.IOUtils;
import java.io.*;
import java.nio.file.Path;
@ -78,7 +77,7 @@ public class ForgeOldInstallTask extends Task<Version> {
ZipEntry forgeEntry = zipFile.getEntry(installProfile.getInstall().getFilePath());
try (InputStream is = zipFile.getInputStream(forgeEntry); OutputStream os = new FileOutputStream(forgeFile)) {
IOUtils.copyTo(is, os);
is.transferTo(os);
}
setResult(installProfile.getVersionInfo()

View File

@ -26,7 +26,6 @@ import org.jackhuang.hmcl.task.FileDownloadTask.IntegrityCheck;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.util.DigestUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -164,7 +163,7 @@ public class LibraryDownloadTask extends Task<Void> {
JarInputStream jar = new JarInputStream(new ByteArrayInputStream(data));
JarEntry entry = jar.getNextJarEntry();
while (entry != null) {
byte[] eData = IOUtils.readFullyWithoutClosing(jar);
byte[] eData = jar.readAllBytes();
if (entry.getName().equals("checksums.sha1")) {
hashes = new String(eData, StandardCharsets.UTF_8).split("\n");
}

View File

@ -25,7 +25,6 @@ import org.jackhuang.hmcl.util.ServerAddress;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.gson.UUIDTypeAdapter;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.IOUtils;
import org.jackhuang.hmcl.util.io.Unzipper;
import org.jackhuang.hmcl.util.platform.Bits;
import org.jackhuang.hmcl.util.platform.*;
@ -420,7 +419,7 @@ public class DefaultLauncher extends Launcher {
}
try (InputStream input = source; OutputStream output = new FileOutputStream(targetFile)) {
IOUtils.copyTo(input, output);
input.transferTo(output);
}
}

View File

@ -21,7 +21,6 @@ import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import org.jackhuang.hmcl.util.function.ExceptionalSupplier;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.IOUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -288,7 +287,7 @@ public class CacheRepository {
try (FileChannel channel = FileChannel.open(indexFile, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
FileLock lock = channel.lock();
try {
ETagIndex indexOnDisk = fromMaybeMalformedJson(IOUtils.readFullyAsStringWithClosing(Channels.newInputStream(channel)), ETagIndex.class);
ETagIndex indexOnDisk = fromMaybeMalformedJson(new String(Channels.newInputStream(channel).readAllBytes(), UTF_8), ETagIndex.class);
Map<String, ETagItem> newIndex = joinETagIndexes(indexOnDisk == null ? null : indexOnDisk.eTag, index.values());
channel.truncate(0);
ByteBuffer writeTo = ByteBuffer.wrap(GSON.toJson(new ETagIndex(newIndex.values())).getBytes(UTF_8));
@ -424,7 +423,7 @@ public class CacheRepository {
try (FileChannel channel = FileChannel.open(indexFile, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
FileLock lock = channel.lock();
try {
Map<String, Object> indexOnDisk = fromMaybeMalformedJson(IOUtils.readFullyAsStringWithClosing(Channels.newInputStream(channel)), mapTypeOf(String.class, Object.class));
Map<String, Object> indexOnDisk = fromMaybeMalformedJson(new String(Channels.newInputStream(channel).readAllBytes(), UTF_8), mapTypeOf(String.class, Object.class));
if (indexOnDisk == null) indexOnDisk = new HashMap<>();
indexOnDisk.putAll(storage);
channel.truncate(0);

View File

@ -52,7 +52,7 @@ public final class HttpMultipartRequest implements Closeable {
addLine(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", name, filename));
addLine("Content-Type: " + contentType);
addLine("");
IOUtils.copyTo(inputStream, stream);
inputStream.transferTo(stream);
addLine("");
return this;
}

View File

@ -62,54 +62,18 @@ public final class IOUtils {
}
}
/**
* Read all bytes to a buffer from given input stream. The stream will not be closed.
*
* @param stream the InputStream being read.
* @return all bytes read from the stream
* @throws IOException if an I/O error occurs.
*/
public static byte[] readFullyWithoutClosing(InputStream stream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream(Math.max(stream.available(), 32));
copyTo(stream, result);
return result.toByteArray();
}
public static String readFullyAsStringWithClosing(InputStream stream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream(Math.max(stream.available(), 32));
copyTo(stream, result);
return result.toString(UTF_8);
}
/**
* Read all bytes to a buffer from given input stream, and close the input stream finally.
*
* @param stream the InputStream being read, closed finally.
* @return all bytes read from the stream
* @throws IOException if an I/O error occurs.
*/
public static ByteArrayOutputStream readFully(InputStream stream) throws IOException {
try (InputStream is = stream) {
ByteArrayOutputStream result = new ByteArrayOutputStream(Math.max(is.available(), 32));
copyTo(is, result);
return result;
public static byte[] readFully(InputStream stream) throws IOException {
try (stream) {
return stream.readAllBytes();
}
}
public static byte[] readFullyAsByteArray(InputStream stream) throws IOException {
return readFully(stream).toByteArray();
}
public static String readFullyAsString(InputStream stream) throws IOException {
return readFully(stream).toString(UTF_8);
return new String(readFully(stream), UTF_8);
}
public static String readFullyAsString(InputStream stream, Charset charset) throws IOException {
return readFully(stream).toString(charset);
}
public static void copyTo(InputStream src, OutputStream dest) throws IOException {
copyTo(src, dest, new byte[DEFAULT_BUFFER_SIZE]);
return new String(readFully(stream), charset);
}
public static void copyTo(InputStream src, OutputStream dest, byte[] buf) throws IOException {

View File

@ -20,7 +20,6 @@ package org.jackhuang.hmcl.util.tree;
import kala.compress.archivers.tar.TarArchiveEntry;
import kala.compress.archivers.tar.TarArchiveReader;
import org.jackhuang.hmcl.util.io.IOUtils;
import java.io.*;
import java.nio.file.Files;
@ -42,7 +41,7 @@ public final class TarFileTree extends ArchiveFileTree<TarArchiveReader, TarArch
try (GZIPInputStream input = new GZIPInputStream(Files.newInputStream(file));
OutputStream output = Files.newOutputStream(tempFile, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)
) {
IOUtils.copyTo(input, output);
input.transferTo(output);
tarFile = new TarArchiveReader(tempFile);
} catch (Throwable e) {
try {