要在Android Studio中不要求WRITE_EXTERNAL_STORAGE权限,可以通过以下方式解决:
String fileName = "myFile.txt";
String content = "Hello, World!";
try {
// 创建文件
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
// 读取文件
FileInputStream fis = openFileInput(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
fis.close();
// 显示文件内容
String fileContent = sb.toString();
Log.d("TAG", fileContent);
} catch (IOException e) {
e.printStackTrace();
}
getExternalFilesDir()
方法获取应用程序的外部存储目录,并在该目录中创建和访问文件。以下是一个示例:String fileName = "myFile.txt";
String content = "Hello, World!";
File file = new File(getExternalFilesDir(null), fileName);
try {
// 创建文件
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
// 读取文件
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
fis.close();
// 显示文件内容
String fileContent = sb.toString();
Log.d("TAG", fileContent);
} catch (IOException e) {
e.printStackTrace();
}
请注意,使用外部存储目录仍然需要READ_EXTERNAL_STORAGE权限,但不需要WRITE_EXTERNAL_STORAGE权限。