全栈工程师开发手册 (作者:栾鹏)
安卓教程全解
安卓文件操作全解:内部文件、公共文件、私有文件、app静态文件。
读内部文件(当前应用程序文件夹下文件)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public 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) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } return str; }
写内部文件(当前应用程序文件夹下文件)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public 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文件夹下面
复制代码
1
2
3
4
5public static InputStream openrawfile(Context context,int id){ InputStream in = context.getResources().openRawResource(id); //R.raw.my return in; }
创建公共文件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14public void creat_publicdir(String publicpath,String filename) { //Environment.getExternalStorageDirectory();//返回外部存储的根目录 File path=Environment.getExternalStoragePublicDirectory(publicpath); //读取公共文件夹,Environment.+xxx //Environment.DIRECTORY_MUSIC音频文件目录,DIRECTORY_ALARMS警示音文件目录,DIRECTORY_DCIM图片片文件目录 //DIRECTORY_DOWNLOADS下载文件目录,DIRECTORY_MOVIES电影文件目录,DIRECTORY_NOTIFICATIONS通知音文件目录 //DIRECTORY_PICTURES图片目录,DIRECTORY_PODCASTS博客的音频文件目录,DIRECTORY_RINGTONES铃声可用文件目录 File file = new File(path,filename); try { file.mkdirs(); //创建目录 } catch (Exception e) { // TODO: handle exception } }
创建私有文件目录,Android/data/下,app卸载后自动删除
复制代码
1
2
3
4
5
6
7
8
9public 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; }
最后
以上就是纯真冷风最近收集整理的关于安卓文件操作全解:内部文件、公共文件、私有文件、app静态文件的全部内容,更多相关安卓文件操作全解内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复