多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Android自助餐之文件存储 - [Android自助餐之文件存储](#) - [保存到应用目录下](#) - [保存到SD卡](#) - [获取SD卡大小](#) - [获取内部存储空间](#) ### 保存到应用目录下 ~~~ //写 FIle file = new File(context.getFilesDir(),"test.txt");//context.getCacheDir();为应用目录下的缓存目录 FileOutputStream fos=new FileOutputStream(file); fos.write("test".getBytes()); fos.close(); //读 FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String str=br.readLine(); ~~~ ### 保存到SD卡 声明权限 ~~~ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ~~~ 获取SD卡状态 ~~~ //判断SD卡状态 String state= Environment.getExternalStorageState(); if(state.equals(Environment.MEDAI_MOUNTED)){ //操作文件 File file = new File(Environment.getExteralStorageDirectory(),"test.txt"); } ~~~ ### 获取SD卡大小 ~~~ File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize=stat.getBlockSize();//获取块大小 long totalBlocks=stats.getBlockCount();//获取总块数 long availableBlocks=stats.getAvailableBlocks();//获取可用块数 //计算大小 long totalSize= blockSize*totalBlocks; long availSize=availableBlocks*totalBlocks; //格式化字符串 String totalStr=Formatter.formatFileSize(context,totalSize); String availStr=Formatter.formatFileSize(context,availSize); ~~~ ### 获取内部存储空间 只需将上述代码中`Environment.getExternalStorageDirectory()`改为`Environment.getDataDirectory()`