zoukankan      html  css  js  c++  java
  • android01

    【文件读取】

    public class Fileservice {

    private Context context; //android 提供的上下文对象

     

    public Fileservice(Context context) {

    super();

    this.context = context;

    }

     

    /**

     * 文件存储

     * @param fileName

     * @param fileContent

     */

    public void savefile(String fileName, //文件名称

     String fileContent //文件内容

    throws Exception{

    // 【上下文对象context提供的openFileOutput方法,可以快速的获取文件输出流对象】

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

    outStr.write(fileContent.getBytes()); //write(byte[] buffer)

    outStr.close();

    }

    /**

     * 文件读取

     * @param fileName

     * @return

     * @throws Exception

     */

    public String read(String fileName) throws Exception

    {

    FileInputStream inStr = context.openFileInput(fileName);

    ByteArrayOutputStream outStr = new ByteArrayOutputStream(); //字节数组流对象

    byte[] buffer = new byte[1024];   //建字节数组

     

    int len = 0;

    while ( ( len = inStr.read(buffer) ) != -1 ) //从指定文件中读取流到buffer中,直到读完

    {

    outStr.write(buffer, 0, len); //先保存到内存,再一次性读入

    }

    byte[] data = outStr.toByteArray();  //得到内存字节数据

     

    String dataString = new String(data);

    return dataString;

    }

     

    }

    //----------------------------

    使用:

    Fileservice fileSvr = new Fileservice(getApplicationContext());

    try {

    fileSvr.savefile(fileName, fileContent);

    Toast.makeText(getApplicationContext(), R.string.success, 1).show(); //提示成功

    catch (Exception e) {

    // TODO: handle exception

    Toast.makeText(getApplicationContext(), R.string.fail, 1).show(); //提示失败

    e.printStackTrace();

    }

     

    PS : Java中使用 public xxx类创建对象时,会在文件顶部自动添加相应的包,C++需要手动添加相应的.h文件。

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    手机怎么知道5G基站的存在?(小区搜索和SSB简介)
    Python中*args,**kwargs两个参数的作用?
    python之jupyter的安装
    国内安装python库速度慢的解决办法
    MOSFET:金属-氧化物半导体场效应晶体管
    C# 小知识点汇总
    ajax和form和七个中间件
    BBS功能分析
    MVC和MTV
    自关联和auth模块
  • 原文地址:https://www.cnblogs.com/Miami/p/3092007.html
Copyright © 2011-2022 走看看