001/*-
002 * #%L
003 * HAPI FHIR - Core Library
004 * %%
005 * Copyright (C) 2014 - 2025 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.util;
021
022import ca.uhn.fhir.i18n.Msg;
023import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
024import org.apache.commons.io.FileUtils;
025
026import java.io.File;
027import java.io.IOException;
028import java.nio.charset.StandardCharsets;
029import java.text.DecimalFormat;
030
031public class FileUtil {
032        // Use "bytes" instead of just "b" because it reads easier in logs
033        private static final String[] UNITS = new String[] {"Bytes", "kB", "MB", "GB", "TB"};
034
035        public static String formatFileSize(long theBytes) {
036                if (theBytes <= 0) {
037                        return "0 " + UNITS[0];
038                }
039                int digitGroups = (int) (Math.log10((double) theBytes) / Math.log10(1024));
040                digitGroups = Math.min(digitGroups, UNITS.length - 1);
041                return new DecimalFormat("###0.#").format(theBytes / Math.pow(1024, digitGroups)) + " " + UNITS[digitGroups];
042        }
043
044        /**
045         * Loads the contents of a File as a UTF-8 encoded string, and wraps any exceptions in an unchecked exception
046         *
047         * @throws InternalErrorException If any IOException occurs
048         */
049        public static String loadFileAsString(File theFile) throws InternalErrorException {
050                try {
051                        return FileUtils.readFileToString(theFile, StandardCharsets.UTF_8);
052                } catch (IOException e) {
053                        throw new InternalErrorException(Msg.code(2592) + e, e);
054                }
055        }
056}