|
1 | 1 | package com.fox2code.mmm.utils; |
2 | 2 |
|
| 3 | +import android.os.Build; |
| 4 | + |
| 5 | +import androidx.annotation.NonNull; |
| 6 | + |
3 | 7 | import com.topjohnwu.superuser.io.SuFile; |
4 | 8 | import com.topjohnwu.superuser.io.SuFileInputStream; |
5 | 9 | import com.topjohnwu.superuser.io.SuFileOutputStream; |
|
18 | 22 | import java.util.zip.ZipOutputStream; |
19 | 23 |
|
20 | 24 | public class Files { |
| 25 | + private static final boolean is64bit = Build.SUPPORTED_64_BIT_ABIS.length > 0; |
| 26 | + |
21 | 27 | public static void write(File file, byte[] bytes) throws IOException { |
22 | 28 | try (OutputStream outputStream = new FileOutputStream(file)) { |
23 | 29 | outputStream.write(bytes); |
@@ -63,8 +69,24 @@ public static void closeSilently(Closeable closeable) { |
63 | 69 | } catch (IOException ignored) {} |
64 | 70 | } |
65 | 71 |
|
| 72 | + public static ByteArrayOutputStream makeBuffer(long capacity) { |
| 73 | + // Cap buffer to 1 Gib (or 512 Mib for 32bit) to avoid memory errors |
| 74 | + return Files.makeBuffer((int) Math.min(capacity, is64bit ? 0x40000000 : 0x20000000)); |
| 75 | + } |
| 76 | + |
| 77 | + public static ByteArrayOutputStream makeBuffer(int capacity) { |
| 78 | + return new ByteArrayOutputStream(Math.max(0x20, capacity)) { |
| 79 | + @NonNull |
| 80 | + @Override |
| 81 | + public byte[] toByteArray() { |
| 82 | + return this.buf.length == this.count ? |
| 83 | + this.buf : super.toByteArray(); |
| 84 | + } |
| 85 | + }; |
| 86 | + } |
| 87 | + |
66 | 88 | public static byte[] readAllBytes(InputStream inputStream) throws IOException { |
67 | | - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); |
| 89 | + ByteArrayOutputStream buffer = Files.makeBuffer(inputStream.available()); |
68 | 90 | copy(inputStream, buffer); |
69 | 91 | return buffer.toByteArray(); |
70 | 92 | } |
|
0 commit comments