package com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* IO 工具类
* @author dingpengcheng
*
*/
public class IoUtil {
/**
* 根据给出的filePath和charsetStr读取文件
* @param filePath 文件路径
* @param charsetStr 字符集名字
* @return 文件内容
*/
public static String readFromFile(String filePath,String charsetStr){
StringBuilder str = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charsetStr));
try {
String subStr;
while((subStr=reader.readLine())!=null){
str.append(subStr);
str.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return str.toString();
}
/**
* 追加写入文件 , 每次追加换行
* @param filePath 文件路径
* @param charsetStr 字符集名字
* @param content 文件内容
*/
public static void writeFile(String filePath, String charsetStr,String content){
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true), charsetStr))) ;
writer.println(content);
} catch (Exception e) {
e.printStackTrace();
}finally {
writer.close();
}
}
/**
* 每次写入重新覆盖
* @param filePath
* @param charsetStr
* @param content
*/
public static void writeFileNoAppend(String filePath , String charsetStr,String content){
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), charsetStr))) ;
writer.println(content);
} catch (Exception e) {
e.printStackTrace();
}finally {
writer.close();
}
}
/**
* 从文件中读取对象
* @param filePath 文件路径
* @return object对象
*/
public static Object readJavaObject(String filePath){
Object obj= null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
try {
obj = in.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 向文件中写入对象,必须保证写入对象全部可序列化
* @param filePath
* @return
*/
public static void writeJavaObject(String filePath, Object obj){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
try {
out.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
转载于:https://my.oschina.net/night4soul/blog/524833