tools.utils.StringUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-autotest-tool Show documentation
Show all versions of java-autotest-tool Show documentation
This is an integration of autotest tools
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();
}
}