android studio数据的本地存储并读写

1.写数据

String string = "要写入的内容";
FileOutputStream fos = null;
 try {
     fos = openFileOutput("文件名", Context.MODE_PRIVATE);
     fos.write(string.getBytes());
     fos.close();
     } catch (FileNotFoundException e) {
                    e.printStackTrace();
    } catch (IOException e) {
                    e.printStackTrace();
    }

2.读数据

try{
    FileInputStream fis = openFileInput("文件名");//与写入对应写入时起的文件名,这里用写入时的名字读取的就是写入时的数据
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = fis.read(buffer)) != -1){
        baos.write(buffer,0,len);
    }
    content3 = baos.toString();//将文件数据赋值给变量content,变量可在你需要且合适的地方定义
        fis.close();
     }catch (Exception e){
       e.printStackTrace();
    }

注:如在读写数据时要刷新页面可调用onCreat(null);函数而且Activity主类必须extends自Activity而不是创建时默认的bar或者com.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐