首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Android中写入SD卡上的文件夹?

如何在Android中写入SD卡上的文件夹?
EN

Stack Overflow用户
提问于 2010-08-24 05:24:43
回答 3查看 180.1K关注 0票数 85

我使用以下代码从我的服务器下载一个文件,然后将其写入SD卡的根目录,一切正常:

代码语言:javascript
复制
package com.downloader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

public class Downloader {

    public void DownloadFile(String fileURL, String fileName) {
        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            FileOutputStream f = new FileOutputStream(new File(root, fileName));

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }

    }
}

但是,使用Environment.getExternalStorageDirectory();意味着文件将始终写入根/mnt/sdcard。是否可以指定要将文件写入的某个文件夹?

例如:/mnt/sdcard/myapp/downloads

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-08-24 05:36:24

代码语言:javascript
复制
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...
票数 162
EN

Stack Overflow用户

发布于 2013-11-21 01:18:42

向Android Manifest添加权限

this WRITE_EXTERNAL_STORAGE permission添加到应用程序清单中。

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

检查外部存储的可用性

您应该始终首先检查可用性。来自the official android documentation on external storage的代码片段。

代码语言:javascript
复制
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

使用文件写入器

最后,同样重要的是,忘记FileOutputStream,改用FileWriter。有关该类的更多信息,请参见the FileWriter javadoc。您可能希望在此处添加更多错误处理,以通知用户。

代码语言:javascript
复制
// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();
票数 32
EN

Stack Overflow用户

发布于 2014-01-30 16:05:31

在这里找到了答案- http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/

上面写着,

代码语言:javascript
复制
/**

* Method to check if user has permissions to write on external storage or not

*/

public static boolean canWriteOnExternalStorage() {
   // get the state of your external storage
   String state = Environment.getExternalStorageState();
   if (Environment.MEDIA_MOUNTED.equals(state)) {
    // if storage is mounted return true
      Log.v("sTag", "Yes, can write to external storage.");
      return true;
   }
   return false;
}

然后让我们使用这段代码来实际写入外部存储:

代码语言:javascript
复制
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "My-File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();

这就是了。如果您现在访问/sdcard/ your -dir-name/文件夹,您将看到一个名为- My- file -Name.txt的文件,其中包含代码中指定的内容。

PS:-您需要以下权限-

代码语言:javascript
复制
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3551821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档