Android下文件访问的权限
* 默认情况下,Android中,应用程序的文件时私有的,其他应用程序不可以读取私有的文件
* 底层用的时Linux文件的权限
- rw- rw- ---
- :文件
r:只读 readable
w:只写 writeable
x: 可执行
第一位:文件类型
234位:应用程序对自己文件的权限
567位:同组用户对这个文件的操作权限
8910位:其他应用程序对文件的权限
package com.example.filemode; import java.io.FileOutputStream; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn1 = (Button) findViewById(R.id.btn1); Button btn2 = (Button) findViewById(R.id.btn2); Button btn3 = (Button) findViewById(R.id.btn3); Button btn4 = (Button) findViewById(R.id.btn4); // 设置监听事件 btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); btn4.setOnClickListener(this); } @Override public void onClick(View v) { try { FileOutputStream fos = null; switch (v.getId()) { case R.id.btn1:// 私有 fos = this.openFileOutput("private.txt", MODE_PRIVATE); break; case R.id.btn2:// 只读 fos = this.openFileOutput("readable.txt", MODE_WORLD_READABLE); break; case R.id.btn3:// 只写 fos = this.openFileOutput("writeable.txt", MODE_WORLD_WRITEABLE); break; case R.id.btn4:// 可读可写 fos = this.openFileOutput("public.txt",MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE); break; default: break; } fos.write("呵呵".getBytes()); fos.close(); Toast.makeText(this, "文件保存成功,哈哈。。。", 0).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "文件保存失败楼", 0).show(); } } }
package com.example.readwrite; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void read(View v){ try { File file = new File("/data/data/com.example.filemode/files/public.txt"); FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String text = br.readLine(); br.close(); Toast.makeText(this, "哈哈:"+text, 0).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "无权读取文件", 0).show(); } } public void write(View v){ File file = new File("/data/data/com.example.filemode/files/public.txt"); try { FileOutputStream fos = new FileOutputStream(file); fos.write("LoaderMan".getBytes()); fos.close(); Toast.makeText(this, "嘿嘿", 0).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "失败了!", 0).show(); } } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!