PrintWriter,FileOutputStream,FileInputStream

10 篇文章 0 订阅

由于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();//关闭输入流

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值