001/* 002 * Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0 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 com.agentsflex.core.util; 017 018import okio.BufferedSink; 019 020import java.io.*; 021import java.nio.charset.StandardCharsets; 022 023public class IOUtil { 024 private static final int DEFAULT_BUFFER_SIZE = 8192; 025 026 public static void writeBytes(byte[] bytes, File toFile) { 027 try (FileOutputStream stream = new FileOutputStream(toFile)) { 028 stream.write(bytes); 029 } catch (IOException e) { 030 throw new UncheckedIOException(e); 031 } 032 } 033 034 public static byte[] readBytes(File file) { 035 try (FileInputStream inputStream = new FileInputStream(file)) { 036 return readBytes(inputStream); 037 } catch (IOException e) { 038 throw new UncheckedIOException(e); 039 } 040 } 041 042 public static byte[] readBytes(InputStream inputStream) { 043 try { 044 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 045 copy(inputStream, outStream); 046 return outStream.toByteArray(); 047 } catch (IOException e) { 048 throw new UncheckedIOException(e); 049 } 050 } 051 052 public static void copy(InputStream inputStream, BufferedSink sink) throws IOException { 053 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 054 for (int len; (len = inputStream.read(buffer)) != -1; ) { 055 sink.write(buffer, 0, len); 056 } 057 } 058 059 public static void copy(InputStream inputStream, OutputStream outStream) throws IOException { 060 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 061 for (int len; (len = inputStream.read(buffer)) != -1; ) { 062 outStream.write(buffer, 0, len); 063 } 064 } 065 066 public static String readUtf8(InputStream inputStream) throws IOException { 067 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 068 copy(inputStream, outStream); 069 return new String(outStream.toByteArray(), StandardCharsets.UTF_8); 070 } 071 072 073}