Home >Java >javaTutorial >How to Write Files to a Specific Folder on the SD Card?

How to Write Files to a Specific Folder on the SD Card?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 20:54:111002browse

How to Write Files to a Specific Folder on the SD Card?

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:

  1. Get the SD card's absolute path:

    File sdCard = Environment.getExternalStorageDirectory();
  2. Create the desired folder:

    File dir = new File (sdCard.getAbsolutePath() + "/myapplication/downloads");
    dir.mkdirs(); // Creates non-existent directories
  3. Create a file within the folder:

    File file = new File(dir, "myfile.txt");
  4. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn