经常会用到输入输出流读写文件,所以就写了一个工具类,方法如下:
public static String readFile(String filePath){
String result="";
try{
FileReader fr=new FileReader(filePath);
char[] data=new char[1024];
int num=fr.read(data);
StringBuffer sb=new StringBuffer();
while(num!=-1){
String str=new String(data,0,num);
sb.append(str);
num=fr.read(data);
}
result=sb.toString();
}catch(IOException e){
System.out.println("读取文件失败");
}
return result;
}
public static boolean writeFile(String str,String filePath){
boolean result=true;
try{
//FileWriter fw=new FileWriter(filePath);
Writer fw = new OutputStreamWriter(new FileOutputStream (filePath),"UTF-8");
fw.write(str);
fw.close();
}catch(IOException e){
result=false;
System.out.println("写文件失败");
}
return result;
}