/**
* 文件读入
* @param filePath 文件路径和名称
* @return
*/
public String fileReader(String filePath) {
//filePath为文件完全限定名
File file = new File(filePath);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileReader reader = null;//定义一个fileReader对象,用来初始化BufferedReader
StringBuilder sb = new StringBuilder();//定义一个字符串缓存,将字符串存放缓存中
BufferedReader bReader = null;
try {
reader = new FileReader(file);
bReader = new BufferedReader(reader);//new一个BufferedReader对象,将文件内容读取到缓存
String s = "";
while ((s =bReader.readLine()) != null) {//逐行读取文件内容,不读取换行符和末尾的空格
sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
}
bReader.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bReader != null ) {
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* 写出文件
* @param str 需要写出的字符串
*/
public void fileWrite(String str,String filePath) {
//filePath为文件完全限定名
File txt=new File(filePath);
FileOutputStream fos = null;
try {
if(!txt.exists()){
txt.createNewFile();
}
byte bytes[]=new byte[512];
bytes=str.getBytes();
int b=bytes.length; //是字节的长度,不是字符串的长度
fos=new FileOutputStream(txt);
fos.write(bytes,0,b);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null ) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}