要在Android應(yīng)用程序中讀寫文件,您需要在AndroidManifest.xml文件中進(jìn)行一些配置。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
這將允許您的應(yīng)用程序讀取和寫入外部存儲(chǔ)器(SD卡)上的文件。
checkSelfPermission()
方法檢查是否已授予這些權(quán)限,并使用requestPermissions()
方法請(qǐng)求權(quán)限。在您的活動(dòng)中添加以下代碼:
private static final int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 權(quán)限已授予,可以進(jìn)行文件讀寫操作
} else {
// 權(quán)限被拒絕,無(wú)法進(jìn)行文件讀寫操作
}
}
}
File file = new File(Environment.getExternalStorageDirectory(), "filename.txt");
try {
// 寫文件
FileWriter writer = new FileWriter(file);
writer.write("Hello, World!");
writer.flush();
writer.close();
// 讀文件
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
reader.close();
Log.d("MyApp", "File content: " + line);
} catch (IOException e) {
e.printStackTrace();
}
以上代碼將文件寫入外部存儲(chǔ)器的根目錄,并讀取文件內(nèi)容并在Logcat中打印出來(lái)。您可以根據(jù)自己的需求更改文件路徑和操作。