java以指定编码格式读写文件工具类:
package cn.geekapp.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* 文件读写类
*/
public class FileUtil {
/**
* 读取文件
* @param file
* @param charset
* @return
*/
public static String readFile(File file, String charset){
if(file == null)
return "";
if(!file.exists())
return "";
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("readFile exception:"+e);
}finally{
try {
if(reader != null)
reader.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
return buffer.toString();
}
/**
* 保存文件
* @param file
* @param content
* @param charset
* @return
*/
public static boolean saveFile(File file, String content, String charset){
if(file == null)
return false;
BufferedWriter writer = null;
boolean flag = false;
try {
if(!file.exists())
file.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
writer.write(content);
writer.flush();
flag = true;
} catch (Exception e) {
// TODO: handle exception
System.out.println("readFile exception:"+e);
}finally{
try {
if(writer != null)
writer.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
return flag;
}
}
原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。