android 读写txt文件

写了两个函数,发现调用时老是异常,原来是openFileOutput 方法必须在Activity中调用。所以一下两个函数都必须在Activity中调用。

public class FileStream{
private Context context;

public FileStream(Context context) {
    this.context = context;
}

/**
 * 
 *@Title:SaveFile
 *@param fileName 需要加后缀,如.txt
 *@param fileContent
 *@throws IOException
 *@Description: 保存文件
 */
public void SaveFileTxt(String fileName, String fileContent)  { 
try{ 

      FileOutputStream fout =context.openFileOutput(fileName,Context.MODE_PRIVATE); 

      byte [] bytes = fileContent.getBytes(); 

      fout.write(bytes); 

      fout.close(); 
    } 

      catch(Exception e){ 
      e.printStackTrace(); 
     }  
}

/**
 *  
 *@Title:ReadFileTxt
 *@param fileName
 *@return 
 *@throws IOException
 *@Description: 读txt文档,返回读出来的数
 */
public String ReadFileTxt(String fileName) throws IOException{ 
    String res=""; 
    try{ 
           FileInputStream fin = context.openFileInput(fileName); 
           int length = fin.available(); 
           byte [] buffer = new byte[length]; 
           fin.read(buffer);     
           res = EncodingUtils.getString(buffer, "UTF-8"); 
           fin.close();     
       } 
       catch(Exception e){ 
           e.printStackTrace(); 
       } 
       return res;      
}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值