Writing to a Folder on the SD Card
Your current code uses Environment.getExternalStorageDirectory() to save files to the root directory of the SD card. To write to a specific folder, follow these steps:
Get the SD card's absolute path:
File sdCard = Environment.getExternalStorageDirectory();
Create the desired folder:
File dir = new File (sdCard.getAbsolutePath() + "/myapplication/downloads"); dir.mkdirs(); // Creates non-existent directories
Create a file within the folder:
File file = new File(dir, "myfile.txt");
Open a file output stream and write data to the file:
FileOutputStream f = new FileOutputStream(file); f.write(...); f.close();
Example Code:
File sdCard = Environment.getExternalStorageDirectory(); File dir = new File (sdCard.getAbsolutePath() + "/myapp/downloads"); dir.mkdirs(); File file = new File(dir, "file.txt"); FileOutputStream f = new FileOutputStream(file); f.write("Hello world!".getBytes()); f.close();
With this approach, you can now write files to any specific folder on the SD card.
The above is the detailed content of How to Write Files to a Specific Folder on the SD Card?. For more information, please follow other related articles on the PHP Chinese website!