每日日报

使用上下文(Context)获取常见目录

Context 可以理解成大工具类
通过上下文 可以访问跟当前应用相关的 全局信息(系统资源) 也可以访问当前应用的私有资源 和类
也可以做系统级的调用 比如 开启另外一个activity 发广播 开启服务
 
getFilesDir(); 操作的是 data/data/包名/files
openFileInput->FileInputStream         这两个方法获取的流实际上操作的就是getFilesDir()对应目录下的文件
openFileOutput->FileOutputStream
 
访问/data/data/包名 这个私有目录 一定要使用上下文获取路径
 
  1. public static boolean saveInfobycontext(Context context,String username, String pwd) {
  2. String info = username+"##"+pwd;
  3. // File file = new File("data/data/com.itheima.logindemo/info.txt");
  4. //使用上下文获取应用相关私有路径
  5. // File file = new File(context.getFilesDir().getAbsolutePath()+"/info.txt");
  6. try {
  7. // FileOutputStream fos = new FileOutputStream(file);
  8. FileOutputStream fos = context.openFileOutput("info2.txt", Context.MODE_PRIVATE);
  9. fos.write(info.getBytes());
  10. fos.close();
  11. return true;
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. return false;
  15. }
  16. }
  17. public static String[] readInfobyContext(Context context){
  18. File file = new File("data/data/com.itheima.logindemo/info.txt");
  19. try {
  20. //FileInputStream fis = new FileInputStream(file);
  21. FileInputStream fis = context.openFileInput("info2.txt");
  22. BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
  23. String temp = reader.readLine();
  24. String[] result = temp.split("##");
  25. return result;
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. return null;
  29. }
  30. }
原文地址:https://www.cnblogs.com/zhukaile/p/14376631.html