All Downloads are FREE. Search and download functionalities are using the official Maven repository.

tools.utils.StringUtils Maven / Gradle / Ivy

There is a newer version: 0.2.2
Show newest version
package tools.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class StringUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(StringUtils.class);

    public static String readFileAsString(String fileName) {
        LOGGER.info("readFileAsString method has been called.");
        String encoding = "utf-8";
        File file = new File(fileName);
        Long filelength = file.length();
        LOGGER.info("filelength={}", filelength);
        byte[] filecontent = new byte[filelength.intValue()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(filecontent);
            return new String(filecontent, encoding);
        } catch (FileNotFoundException e) {
            LOGGER.info(e.getMessage());
            return null;
        } catch (IOException e) {
            LOGGER.info(e.getMessage());
            return null;
        }
    }

    public static String readFileFromResourceAsString(String fileName) {
        LOGGER.info("readFileFromResourceAsString method has been called.");
        StringBuilder stringBuilder = new StringBuilder();
        FileInputStream fileInputStream = null;
        BufferedReader reader = null;
        try {
            // Getting ClassLoader obj
            ClassLoader classLoader = StringUtils.class.getClassLoader();
            // Getting resource(File) from class loader
            File configFile = new File(classLoader.getResource(fileName).getFile());
            fileInputStream = new FileInputStream(configFile);
            reader = new BufferedReader(new InputStreamReader(fileInputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            try {
                if (reader != null){
                    reader.close();
                    LOGGER.debug("reader关闭。");
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                    LOGGER.debug("fileInputStream关闭。");
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
        return stringBuilder.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy