使用上下文(Context)获取常见目录
Context 可以理解成大工具类
通过上下文 可以访问跟当前应用相关的 全局信息(系统资源) 也可以访问当前应用的私有资源 和类
也可以做系统级的调用 比如 开启另外一个activity 发广播 开启服务
getFilesDir(); 操作的是 data/data/包名/files
openFileInput->FileInputStream 这两个方法获取的流实际上操作的就是getFilesDir()对应目录下的文件
openFileOutput->FileOutputStream
访问/data/data/包名 这个私有目录 一定要使用上下文获取路径
public static boolean saveInfobycontext(Context context,String username, String pwd) {
String info = username+"##"+pwd;
// File file = new File("data/data/com.itheima.logindemo/info.txt");
//使用上下文获取应用相关私有路径
// File file = new File(context.getFilesDir().getAbsolutePath()+"/info.txt");
try {
// FileOutputStream fos = new FileOutputStream(file);
FileOutputStream fos = context.openFileOutput("info2.txt", Context.MODE_PRIVATE);
fos.write(info.getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static String[] readInfobyContext(Context context){
File file = new File("data/data/com.itheima.logindemo/info.txt");
try {
//FileInputStream fis = new FileInputStream(file);
FileInputStream fis = context.openFileInput("info2.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String temp = reader.readLine();
String[] result = temp.split("##");
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}