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

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    Windows下开发过程中常用的Linux指令
    flask sqlalchemy实现分页功能
    channel(3) 一 基本定义
    goroutine(2) goroutine同步
    goroutine(1) go的调度器
    go 语言 interface(接口 二)
    go 语言 interface(接口 一)
    go 语言 defer
    go 语言 闭包
    go 语言 函数
  • 原文地址:https://www.cnblogs.com/Miami/p/3092007.html
Copyright © 2011-2022 走看看