android 文本操作

编辑于2016年

内部存储

preferences保存

//保存数据到文件      
 //多个preferences时实用命名读取和创建//        SharedPreferences sharedPreferences = getSharedPreferences("bartest",this.MODE_PRIVATE);        
//只有一个preference时        
SharedPreferences preference = getPreferences(this.MODE_PRIVATE);//获取编辑句柄        SharedPreferences.Editor editor = preference.edit();editor.putString("userName","krock");
editor.commit();// 完成保存       
 //读取数据      
 // String userName = preference.getString("userName","app");


文件保存

//简单的一个写入文件步骤
String filename = "myfile";String word = "hello World";
FileOutputStream fileOutputStream;
try{fileOutputStream = openFileOutput(filename,this.MODE_PRIVATE);
fileOutputStream.write(word.getBytes());
fileOutputStream.close();
}catch (Exception ex){
ex.getStackTrace();
}
//缓存空间存储
 file = File.createTempFile(fileName, null, context.getCacheDir());

外部存储

获取存储卡状态

/* Checks if external storage is available for read and write */public boolean isExternalStorageWritable() { 
   String state = Environment.getExternalStorageState();   
if (Environment.MEDIA_MOUNTED.equals(state)) {        
return true;    
}    
return false;
}/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {    
String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {        return true;
    } 
   return false;}

创建公共文件

public File getAlbumStorageDir(String albumName) {    
// Get the directory for the user's public pictures directory.
    File file = new File(Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) { 
       Log.e(LOG_TAG, "Directory not created");
    } 
   return file;}

创建私有文件

文件会在用户卸载我们的app时被系统删除

public File getAlbumStorageDir(Context context, String albumName) { 
   // Get the directory for the app's private pictures directory. 
   File file = new File(context.getExternalFilesDir(            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }   
 return file;}

获取剩余空间

getFreeSpace()

删除文件

在不需要使用某些文件的时候应删除它。删除文件最直接的方法是直接执行文件的delete()
方法。

myFile.delete();

如果文件是保存在internal storage,我们可以通过Context
来访问并通过执行deleteFile()
进行删除

myContext.deleteFile(fileName);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • 一、保存到SharedPreference SharedPreferences 对象指向一个保存key-value...
    brant_feeboo阅读 512评论 0 1
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,626评论 0 17
  • 之前闲着无聊,研究了下 Android 存储方面的知识,顺便翻译了下官方文档(虽然有已经被翻译过...)。这里就算...
    koguma阅读 1,032评论 0 3
  • 《金刚经》 金刚经 第一品 法会因由分 如是我闻。一时佛在舍卫国。祗树给孤独园。与大比丘众。千二百五十人俱。尔时世...
    花在手中阅读 269评论 0 2