Tôi đang sử dụng các mã sau đây để tải về một tập tin từ máy chủ của tôi sau đó viết nó vào thư mục gốc của thẻ sd, tất cả đều hoạt động tốt:
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());
}
}
}
Tuy nhiên, sử dụng Environment.getExternalStorageDirectory();
có nghĩa là tệp sẽ luôn ghi vào thư mục gốc /mnt/sdcard
. Có thể chỉ định một thư mục nhất định để ghi tệp vào không?
Ví dụ: /mnt/sdcard/myapp/downloads
Chúc mừng
Eef
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);
...
Thêm quyền vào tệp kê khai Android
Thêm vào quyền WRITE_EXTERNAL_STORAGE này vào tệp kê khai ứng dụng của bạn.
<?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>
Kiểm tra tính khả dụng của bộ nhớ ngoài
Bạn nên luôn luôn kiểm tra tính khả dụng trước. Đoạn trích từ tài liệu android chính thức về bộ nhớ ngoài.
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;
}
Sử dụng một Filewriter
Cuối cùng nhưng không kém phần quên về FileOutputStream
và sử dụng FileWriter
thay thế. Thông tin thêm về biểu mẫu lớp học đó FileWriter javadoc. Bạn có thể muốn thêm một số lỗi xử lý ở đây để thông báo cho người dùng.
// 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();
Tìm thấy câu trả lời ở đây - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/
Nó nói rằng,
/**
* 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;
}
và sau đó hãy sử dụng mã này để thực sự ghi vào bộ nhớ ngoài:
// 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();
Và đây là nó. Nếu bây giờ bạn truy cập vào thư mục / sdcard / your-dir-name / bạn sẽ thấy một tệp có tên là My-File-Name.txt với nội dung như được chỉ định trong mã.
PS: - Bạn cần sự cho phép sau -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Để tải xuống tệp để Tải xuống hoặc thư mục nhạc trong thẻ SDCard
File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES
Và đừng quên thêm các quyền này vào tệp kê khai
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />