您的位置:首页 > 移动开发 > Android开发

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

2014-07-24 16:39 387 查看
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: