全栈工程师开发手册 (作者:栾鹏)
安卓教程全解
安卓文件操作全解:内部文件、公共文件、私有文件、app静态文件。
读内部文件(当前应用程序文件夹下文件)
public static String openfile(Context context,String filename) {
String str = null;
FileInputStream in = null;
try {
in = context.openFileInput(filename);
byte[] b = new byte[1024];
int length = in.read(b);
str = new String(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
写内部文件(当前应用程序文件夹下文件)
public static void writefile(Context context,String filename,String data){
FileOutputStream out = null;
try {
out = context.openFileOutput(filename,Context.MODE_APPEND); //使用MODE_APPEND 在添加模式中打开文件,MODE_PRIVATE不覆盖
out.write(data.getBytes());
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
try {
out.close();
File file = context.getFilesDir(); //getFilesDir()获取你app的内部存储空间,相当于你的应用在内部存储上的根目录
Log.d("path", file.getAbsolutePath());
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
读取静态文件,读取res文件夹raw文件夹下面
public static InputStream openrawfile(Context context,int id){
InputStream in = context.getResources().openRawResource(id);
return in;
}
创建公共文件
public void creat_publicdir(String publicpath,String filename) {
File path=Environment.getExternalStoragePublicDirectory(publicpath);
File file = new File(path,filename);
try {
file.mkdirs();
} catch (Exception e) {
}
}
创建私有文件目录,Android/data/下,app卸载后自动删除
public File getAlbumStorageDir(Context context, String pritivepath,String filename) {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
if(!file.mkdirs()) {
Log.e("file", "Directory not created");
}
return file;
}
|