由于PrintWriter的简便性,即只需要print()语句即可输出任何内容,因此用到这个类的次数非常多,但是我经常会忽视在构造方法中:new PrintWriter(new FileOutputStream(),true);
如果没有加这个true,后果非常匪夷所思。。。
不仅在文件流的操作,而且在网络编程Socket时,也会通过PrintWriter包装Socket的输出流,如果没有加true,则输出的东西不会在另一端取得;会抛出异常;
static PrintWriter pWriter=null;
//文件存放目录
public static String appDir=Environment.getExternalStorageDirectory().getPath().toString()+"/tankguard";
//异常文件存储目录
public static String appExceptionDir=appDir+"/Exception";
(Exception e)
{
String fileName = appExceptionDir+"/a.txt";
File dirFile=new File(appExceptionDir);
File file=new File(fileName);
if(!dirFile.exists())
{
dirFile.mkdir();
}
if(!file.exists())
{
file.createNewFile();
}
FileWriter fstream = new FileWriter(fileName, true);
BufferedWriter out = new BufferedWriter(fstream);
pWriter = new PrintWriter(out, true);
e.printStackTrace(pWriter);
}
写文件
Context.openFileOutput(String name,int mode)开启一个与应用程序联系的私有文件输出流
当文件不存在时该文件将被创建
文件输出流可以在添加模式中打开,这意味新的数据将被添加到文件的末尾
FileOutputStream out = this.openFileOutput("test2.txt",MODE_APPEND);
//打开文件"test2.txt"进行写操作、使用MODE_APPEND 在添加模式中打开文件
……
out.close();//关闭输出流
InputStream is = getAssets().open("setting.xml");
try{
FileOutputStream fout =new FileOutputStream(setFilePath);
int length = is.available();
byte [] buffer = new byte[length];
is.read(buffer);
is.close();
fout.write(buffer);
fout.close();
}
读文件
Context.openFileInput(String name)打开一个与应用程序联系的私有文件输入流
当文件不存在时抛出FileNotFoundException 异常
FileInputStream in = this.openFileInput("test2.txt");//打开文件"test2.txt"
……
in.close();//关闭输入流