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
Release: 2024-12-05 20:54:11
Original
961 people have browsed it

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();
    Copy after login
  2. Create the desired folder:

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

    File file = new File(dir, "myfile.txt");
    Copy after login
  4. Open a file output stream and write data to the file:

    FileOutputStream f = new FileOutputStream(file);
    f.write(...);
    f.close();
    Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template