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.file2text.util; 017 018import java.io.ByteArrayOutputStream; 019import java.io.IOException; 020import java.io.InputStream; 021import java.io.OutputStream; 022 023public class IOUtils { 024 private static final int BUFFER_SIZE = 8192; 025 026 public static byte[] toByteArray(InputStream is, long maxSize) { 027 ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 028 copyStream(is, buffer, maxSize); 029 return buffer.toByteArray(); 030 } 031 032 public static void copyStream(InputStream is, OutputStream os, long maxSize) { 033 byte[] buffer = new byte[BUFFER_SIZE]; 034 int bytesRead; 035 long total = 0; 036 try { 037 while ((bytesRead = is.read(buffer)) != -1) { 038 if (total + bytesRead > maxSize) { 039 throw new RuntimeException("Stream too large: limit is " + maxSize + " bytes"); 040 } 041 os.write(buffer, 0, bytesRead); 042 total += bytesRead; 043 } 044 } catch (IOException e) { 045 throw new RuntimeException(e); 046 } 047 } 048}