001/**
002 * Copyright (c) 2025-2026, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.gnu.org/licenses/lgpl-3.0.txt
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package dev.tinyflow.core.util;
017
018import okio.BufferedSink;
019
020import java.io.*;
021import java.nio.charset.StandardCharsets;
022
023public class IOUtil {
024
025    public static void writeBytes(byte[] bytes, File toFile) {
026        try (FileOutputStream stream = new FileOutputStream(toFile)) {
027            stream.write(bytes);
028        } catch (IOException e) {
029            throw new RuntimeException(e);
030        }
031    }
032
033    public static byte[] readBytes(File file) {
034        try (FileInputStream inputStream = new FileInputStream(file)) {
035            return readBytes(inputStream);
036        } catch (IOException e) {
037            throw new RuntimeException(e);
038        }
039    }
040
041    public static byte[] readBytes(InputStream inputStream) {
042        try {
043            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
044            copy(inputStream, outStream);
045            return outStream.toByteArray();
046        } catch (IOException e) {
047            throw new RuntimeException(e);
048        }
049    }
050
051    public static void copy(InputStream inputStream, BufferedSink sink) throws IOException {
052        byte[] buffer = new byte[2048];
053        for (int len; (len = inputStream.read(buffer)) != -1; ) {
054            sink.write(buffer, 0, len);
055        }
056    }
057
058    public static void copy(InputStream inputStream, OutputStream outStream) throws IOException {
059        byte[] buffer = new byte[2048];
060        for (int len; (len = inputStream.read(buffer)) != -1; ) {
061            outStream.write(buffer, 0, len);
062        }
063    }
064
065    public static String readUtf8(InputStream inputStream) throws IOException {
066        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
067        copy(inputStream, outStream);
068        return new String(outStream.toByteArray(), StandardCharsets.UTF_8);
069    }
070
071
072}