class IOHelper {

    public static InputStream bufferStream(InputStream in, int maxMemSize) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesNum;
        boolean overflow = false;
        while ((!overflow) && (bytesNum = in.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesNum);
            overflow = bos.size() > maxMemSize;
        }

        if (overflow) {
            File file = FileCollector.getInstance().createFile();
            try (FileOutputStream fos = new FileOutputStream(file)) {
                bos.writeTo(fos);
                while ((bytesNum = in.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesNum);
                }
            }
            return new DeleteOnCloseFIS(file);
        }
        return new ByteArrayInputStream(bos.toByteArray());
    }

    private  IOHelper();

}