现在的位置: 首页 > 综合 > 正文

android 读写文件(包括从sdcard中)

2018年01月24日 ⁄ 综合 ⁄ 共 1782字 ⁄ 字号 评论关闭

1、从应用程序目录中读取文件:(不需要特殊权限)

文件被保存到了/data/data/报名/files/ 下。

public static void rememberInfo(Context context,String userName,String passwd) {
try {
FileOutputStream fos =context.openFileOutput("abc.txt",Context.MODE_PRIVATE);
BufferedOutputStream fs = new BufferedOutputStream(fos);

fs.write((userName+";"+passwd).getBytes());
fs.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getUserInfo (Context context) {
String res = "";
try {
FileInputStream  fis = context.openFileInput("abc.txt");
InputStreamReader isr = new InputStreamReader (fis);
BufferedReader br = new BufferedReader(isr);

res=br.readLine();
br.close();
isr.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}


2、从sdcard中读取文件:

 1)写文件时需要有android.permission.WRITE_EXTERNAL_STORAGE 权限;android4以后,从sdcard卡中读取文件也需要有权限;

 2)从sdcard存取时,一般都需要判断sdcard的状态;

public static void rememberInfo4Sd(Context context,String userName,String passwd) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {//判断sdcard是否挂载
File file = new File(Environment.getExternalStorageDirectory(),"abc.txt");
try {
FileOutputStream fo = new FileOutputStream(file);
BufferedOutputStream bo = new BufferedOutputStream(fo);
bo.write((userName+";"+passwd).getBytes());

bo.close();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}

} else {
Toast.makeText(context, "请检查sd卡是否安装好", Toast.LENGTH_SHORT).show();
}
}

public static String getUserInfo4sd(Context context) {
String res = "";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {//判断sdcard是否挂载
File file = new File(Environment.getExternalStorageDirectory(),"abc.txt");
try {
FileInputStream fi = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader (fi);
BufferedReader br = new BufferedReader(isr);

res=br.readLine();
br.close();
isr.close();
fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
}

抱歉!评论已关闭.