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文件。

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    Linux开发环境必备十大开发工具
    mysql executemany与 insert ... ON DUPLICATE KEY UPDATE 一起使用
    python LD_LIBRARY_PATH 靠谱解决办法
    搭建简单ftp,满足windows和ubuntu共享文件
    用类方法作为装饰器装饰同属于本类的另一个方法
    通过类方法名调用类方法
    java将jpg文件转化为base64字节(互转)
    CSS元素居中的方式
    T-SQL语法学习一(持续更新)
    SVN的使用教程(一)
  • 原文地址:https://www.cnblogs.com/Miami/p/3092007.html
Copyright © 2011-2022 走看看