Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy thông tin thư mục dữ liệu hệ thống Android

Giới thiệu

Sử dụng Environment.getDataDirectory() để lấy đường dẫn thư mục dữ liệu hệ thống (thường là /data).

Code (MainActivity.java)

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);

        File dataDir = Environment.getDataDirectory();
        textView.setText("Thư mục data: " + dataDir.getAbsolutePath() +
                         "\nTên: " + dataDir.getName() +
                         "\nCó tồn tại: " + dataDir.exists() +
                         "\nCó ghi được: " + dataDir.canWrite());
    }
}

Kết quả mẫu

Thư mục data: /data
Tên: data
Có tồn tại: true
Có ghi được: false

Các thư mục hữu ích khác

Phương thứcMô tảVí dụ đường dẫn
Environment.getRootDirectory()Thư mục root hệ thống/system
Environment.getExternalStorageDirectory()Bộ nhớ chia sẻ (deprecated API 29)/storage/emulated/0
Context.getFilesDir()Thư mục private của app/data/user/0/pkg/files
Context.getCacheDir()Thư mục cache của app/data/user/0/pkg/cache
Context.getExternalFilesDir(null)Thư mục private trên shared storage/storage/emulated/0/Android/data/pkg/files

Lưu ý

  • getDataDirectory() trả về thư mục gốc chứa dữ liệu người dùng, app cài đặt, database... App thường không có quyền ghi trực tiếp vào đây.
  • Từ Android 10 (API 29), khuyến khích dùng Scoped Storage (Context.getExternalFilesDir) thay vì truy cập shared storage trực tiếp.