// 读取文件内容,避免乱码,filePathAndName是文件绝对路径如c:\\1.txt
public static String readFile(String filePathAndName)
{
String fileContent = "";
try
{
File f = new File(filePathAndName);
if (f.isFile() && f.exists())
{
InputStreamReader read = new InputStreamReader(new FileInputStream(f), "UTF-8");
BufferedReader reader = new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null)
{
fileContent += line;
}
read.close();
}
}
catch (Exception e)
{
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
return fileContent;
}
// 写入文件内容,避免乱码
public static void writeFile(String filePathAndName, String fileContent)
{
try
{
File f = new File(filePathAndName);
if (!f.exists())
{
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
BufferedWriter writer = new BufferedWriter(write);
// PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
// PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
writer.write(fileContent);
writer.close();
}
catch (Exception e)
{
System.out.println("写文件内容操作出错");
e.printStackTrace();
}
}
原帖地址:http://ccgkren.iteye.com/blog/1517423