Java Android写入sd卡文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3551821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android write to sd card folder
提问by RailsSon
I am using the following code to download a file from my server then write it to the root directory of the sd card, it all works fine:
我正在使用以下代码从我的服务器下载文件,然后将其写入 SD 卡的根目录,一切正常:
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());
}
}
}
However, using Environment.getExternalStorageDirectory();
means that the file will always write to the root /mnt/sdcard
. Is it possible to specify a certain folder to write the file to?
但是, usingEnvironment.getExternalStorageDirectory();
意味着文件将始终写入 root /mnt/sdcard
。是否可以指定某个文件夹来写入文件?
For example: /mnt/sdcard/myapp/downloads
例如: /mnt/sdcard/myapp/downloads
Cheers
干杯
Eef
埃夫
采纳答案by plugmind
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);
...
回答by hcpl
Add Permission to Android Manifest
向 Android 清单添加权限
Add this WRITE_EXTERNAL_STORAGE permissionto your applications manifest.
将此 WRITE_EXTERNAL_STORAGE 权限添加到您的应用程序清单。
<?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>
Check availability of external storage
检查外部存储的可用性
You should always check for availability first. A snippet from the official android documentation on external storage.
您应该始终首先检查可用性。来自外部存储官方 android 文档的片段。
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;
}
Use a Filewriter
使用文件编写器
At last but not least forget about the FileOutputStream
and use a FileWriter
instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.
最后但并非最不重要的是忘记FileOutputStream
并使用 aFileWriter
代替。有关该类的更多信息来自FileWriter javadoc。您可能希望在此处添加更多错误处理以通知用户。
// 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();
回答by alchemist
Found the answer here - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/
在这里找到答案 - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/
It says,
它说,
/**
* 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;
}
and then let's use this code to actually write to the external storage:
然后让我们使用此代码实际写入外部存储:
// 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();
And this is it. If now you visit your /sdcard/your-dir-name/ folder you will see a file named - My-File-Name.txt with the content as specified in the code.
就是这样。如果现在您访问您的 /sdcard/your-dir-name/ 文件夹,您将看到一个名为 - My-File-Name.txt 的文件,其中包含代码中指定的内容。
PS:- You need the following permission -
PS:- 您需要以下权限-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
回答by Jawad Zeb
In order to download a file to Download or Music Folder In SDCard
为了将文件下载到 SDCard 中的下载或音乐文件夹
File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES
And dont forget to add these permission in manifest
并且不要忘记在清单中添加这些权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />