package
com.at21.server.collectmanage.monitor.kompsat.utils;
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileWriter;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.io.LineNumberReader;
import
java.io.StringReader;
import
java.io.UnsupportedEncodingException;
import
org.apache.commons.logging.Log;
import
org.apache.commons.logging.LogFactory;
public class
StringFileToolkit {
private static Log log
= LogFactory.getLog(StringFileToolkit.class);
public static String
file2String(InputStream is) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(is));
StringBuilder sBuilder
= new StringBuilder();
String line =
null;
try {
while
((line=reader.readLine())!=null) {
sBuilder.append(line);
}
} catch (Exception e)
{
e.printStackTrace();
} finally {
try {
is.close();
} catch (Exception e2)
{
e2.printStackTrace();
}
}
return
sBuilder.toString();
}
public static String
file2String(File file, String charset) {
StringBuffer sb = new
StringBuffer();
try {
LineNumberReader reader
= new LineNumberReader(new BufferedReader(
new
InputStreamReader(new FileInputStream(file), charset)));
String line;
while ((line =
reader.readLine()) != null) {
sb.append(line).append(System.getProperty("line.separator"));
}
} catch
(UnsupportedEncodingException e) {
log.error("读取文件为一个内存字符串失败,失败原因是使用了不支持的字符编码" + charset, e);
} catch
(FileNotFoundException e) {
log.error("读取文件为一个内存字符串失败,失败原因所给的文件" + file + "不存在!", e);
} catch (IOException e)
{
log.error("读取文件为一个内存字符串失败,失败原因是读取文件异常!", e);
}
return
sb.toString();
}
public static boolean
string2File(String text, File distFile) {
if
(!distFile.getParentFile().exists())
distFile.getParentFile().mkdirs();
BufferedReader br =
null;
BufferedWriter bw =
null;
boolean flag =
true;
try {
br = new
BufferedReader(new StringReader(text));
bw = new
BufferedWriter(new FileWriter(distFile));
char buf[] = new
char[1024 * 64]; // 字符缓冲区
int len;
while ((len =
br.read(buf)) != -1) {
bw.write(buf, 0,
len);
}
bw.flush();
br.close();
bw.close();
} catch (IOException e)
{
flag = false;
log.error("将字符串写入文件发生异常!", e);
}
return flag;
}
}