Home >Java >javaTutorial >How to Specify a Folder on an Android SD Card for File Writing?

How to Specify a Folder on an Android SD Card for File Writing?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 15:34:15871browse

How to Specify a Folder on an Android SD Card for File Writing?

Writing Files to a Specified Folder on an SD Card in Android

In the provided Android code snippet, the file is written to the root directory of the SD card using Environment.getExternalStorageDirectory(). To specify a particular folder, you can use the following steps:

  1. Obtain a reference to the external storage directory:
File sdCard = Environment.getExternalStorageDirectory();
  1. Create a File object for the desired directory path:
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
  1. Create the directory if it doesn't exist using mkdirs():
dir.mkdirs();
  1. Create a File object for the file to be written:
File file = new File(dir, "filename");
  1. Open an FileOutputStream for the file:
FileOutputStream f = new FileOutputStream(file);

By following these steps, you can specify a specific folder on the SD card to write the downloaded file to. Remember to replace "/dir1/dir2" with the actual path to the desired directory.

The above is the detailed content of How to Specify a Folder on an Android SD Card for File Writing?. 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