IO 详解 ,input与output 是以内存作为参考
先上两个demo:
第一个是直接写文件
public static boolean writeFileContent(File file,String context,boolean append) throws IOException{
FileOutputStream fos = null;
OutputStreamWriter pw = null;
boolean result=false;
try {
fos = new FileOutputStream(file,append);
pw = new OutputStreamWriter(fos, "UTF-8");
pw.write(context);
pw.flush();
result=true;
} catch (Exception e) {
e.printStackTrace();
}finally {
//不要忘记关闭
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
}
return result;
}
第二个,先读取再写入:
public static boolean writeFileContent(String p,String fileName,String newstr) throws IOException{
Boolean bool = false;
String filein = newstr;//新写入的行,换行
String temp = "";
String filepath=p+"/"+fileName+".txt";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filepath);//文件路径(包括文件名称)
//将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();
//文件原有内容
for(int i=0;(temp =br.readLine())!=null;i++){
buffer.append(temp);
// 行与行之间的分隔符 相当于“\n”
buffer = buffer.append(System.getProperty("line.separator"));
}
buffer.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buffer.toString().toCharArray());
pw.flush();
bool = true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
//不要忘记关闭
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return bool;
}
博客参考:
http://blog.csdn.net/u010041075/article/details/49007731