Android如何将文件保存到指定路径?自定义应用存储路径方法
Hey there! I see you want to switch from saving files to the internal app private directory (/data/data/com.mypackage.app/files/) to the external app private directory (Internal Storage/Android/data/com.mypackage.app/files/). Let's break down how to fix this properly.
Key Background
The path you're targeting (Internal Storage/Android/data/...) is Android's recommended external storage private directory for your app. Unlike public external storage, this directory:
- Doesn't require the
WRITE_EXTERNAL_STORAGEpermission (for Android 4.4 / API 19 and above) - Gets automatically deleted when your app is uninstalled
- Is private to your app (other apps can't access it without special permissions)
Fixing Your Code
The main issue with your current code is that you're using getFilesDir(), which points to the internal storage private directory. Instead, use getExternalFilesDir(null) to get the correct external private directory path.
Here's the modified version of your createFile() method:
public void createFile() { // Get the external app private directory (this is the path you want) File externalFilesDir = this.getExternalFilesDir(null); // Check if external storage is available to avoid null pointer exceptions if (externalFilesDir == null) { // Handle unavailable external storage (e.g., SD card unmounted) Toast.makeText(this, "External storage is not available", Toast.LENGTH_SHORT).show(); return; } String fileName = "myfiles.txt"; // Matches your desired filename String value = "example value"; File output = new File(externalFilesDir, fileName); // Safe path joining via File constructor try { FileOutputStream fileout = new FileOutputStream(output); OutputStreamWriter outputWriter = new OutputStreamWriter(fileout); outputWriter.write(value); outputWriter.close(); fileout.close(); // Optional: Confirm success to the user Toast.makeText(this, "File created successfully", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "Error creating file", Toast.LENGTH_SHORT).show(); } }
Important Notes
- Why
getExternalFilesDir(null)? Passingnullgives you the root of your app's external private files directory. If you wanted to organize files into subfolders (like "documents" or "images"), you could pass a specific type (e.g.,Environment.DIRECTORY_DOCUMENTS), butnullworks perfectly for your root files path. - Path Safety: Using
new File(externalFilesDir, fileName)is safer than manually joining paths withFile.separator—it handles OS-specific path separators automatically. - Error Handling: Always check if
getExternalFilesDir()returnsnull—this can happen if the external storage is unmounted (e.g., user removed the SD card on older devices).
内容的提问来源于stack exchange,提问作者qwerty

