|
1 | 1 | package io.sentry.util; |
2 | 2 |
|
| 3 | +import java.io.BufferedInputStream; |
3 | 4 | import java.io.BufferedReader; |
| 5 | +import java.io.ByteArrayOutputStream; |
4 | 6 | import java.io.File; |
| 7 | +import java.io.FileInputStream; |
5 | 8 | import java.io.FileReader; |
6 | 9 | import java.io.IOException; |
7 | 10 | import org.jetbrains.annotations.ApiStatus; |
@@ -60,4 +63,57 @@ public static boolean deleteRecursively(@Nullable File file) { |
60 | 63 | } |
61 | 64 | return contentBuilder.toString(); |
62 | 65 | } |
| 66 | + |
| 67 | + /** |
| 68 | + * Reads the content of a path into a byte array. If the path is does not exists, |
| 69 | + * it's not a file, can't be read or is larger than max size allowed IOException |
| 70 | + * is thrown. Do not use with large files, as the byte array is kept in memory! |
| 71 | + * |
| 72 | + * @param pathname file to read |
| 73 | + * @return a byte array containing all the content of the file |
| 74 | + * @throws IOException In case of error reading the file |
| 75 | + */ |
| 76 | + public static byte[] readBytesFromFile(String pathname, long maxFileLength) |
| 77 | + throws IOException, SecurityException { |
| 78 | + File file = new File(pathname); |
| 79 | + |
| 80 | + if (!file.exists()) { |
| 81 | + throw new IOException( |
| 82 | + String.format( |
| 83 | + "File '%s' doesn't exists", |
| 84 | + file.getName())); |
| 85 | + } |
| 86 | + |
| 87 | + if (!file.isFile()) { |
| 88 | + throw new IOException( |
| 89 | + String.format( |
| 90 | + "Reading path %s failed, because it's not a file.", |
| 91 | + pathname)); |
| 92 | + } |
| 93 | + |
| 94 | + if (!file.canRead()) { |
| 95 | + throw new IOException( |
| 96 | + String.format("Reading the item %s failed, because can't read the file.", pathname)); |
| 97 | + } |
| 98 | + |
| 99 | + if (file.length() > maxFileLength) { |
| 100 | + throw new IOException( |
| 101 | + String.format( |
| 102 | + "Reading file failed, because size located at '%s' with %d bytes is bigger " |
| 103 | + + "than the maximum allowed size of %d bytes.", |
| 104 | + pathname, file.length(), maxFileLength)); |
| 105 | + } |
| 106 | + |
| 107 | + try (FileInputStream fileInputStream = new FileInputStream(pathname); |
| 108 | + BufferedInputStream inputStream = new BufferedInputStream(fileInputStream); |
| 109 | + ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { |
| 110 | + byte[] bytes = new byte[1024]; |
| 111 | + int length; |
| 112 | + int offset = 0; |
| 113 | + while ((length = inputStream.read(bytes)) != -1) { |
| 114 | + outputStream.write(bytes, offset, length); |
| 115 | + } |
| 116 | + return outputStream.toByteArray(); |
| 117 | + } |
| 118 | + } |
63 | 119 | } |
0 commit comments