• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package com.ohos.hapsigntool.codesigning.utils;
17 
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 
23 /**
24  * InputStream util class
25  *
26  * @since 2023/08/10
27  */
28 public class InputStreamUtils {
29     private static final int BUFFER_SIZE = 4096;
30 
31     /**
32      * get byte array by inputStream and size
33      *
34      * @param inputStream     inputStream data
35      * @param inputStreamSize inputStream size
36      * @return byte array value
37      * @throws IOException io error
38      */
toByteArray(InputStream inputStream, int inputStreamSize)39     public static byte[] toByteArray(InputStream inputStream, int inputStreamSize) throws IOException {
40         if (inputStreamSize == 0) {
41             return new byte[0];
42         }
43         if (inputStreamSize < 0) {
44             throw new IllegalArgumentException("inputStreamSize: " + inputStreamSize + "is less than zero: ");
45         }
46         try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
47             copy(inputStream, inputStreamSize, output);
48             return output.toByteArray();
49         }
50     }
51 
copy(InputStream inputStream, int inputStreamSize, OutputStream output)52     private static int copy(InputStream inputStream, int inputStreamSize, OutputStream output) throws IOException {
53         byte[] buffer = new byte[BUFFER_SIZE];
54         int readSize = 0;
55         int count = 0;
56         while (readSize < inputStreamSize && (readSize = inputStream.read(buffer)) != -1) {
57             output.write(buffer, 0, readSize);
58             count += readSize;
59         }
60         if (count != inputStreamSize) {
61             throw new IOException("read size err. readSizeCount: " + count + ", inputStreamSize: " + inputStreamSize);
62         }
63         return count;
64     }
65 }
66