Cũng tương tự nhưLưu tập tin ở bộ nhớ trong(internal storage), chúng ta có thể lưu cùng đọc dữ liệu từ bộ nhớ lưu trữ ngoài (external storage) của sản phẩm công nghệ nhưsdcard. Hai lớp FileInputStream và FileOutputStream được thực hiện để đọc và ghi dữ liệu vào tập tin.
Bạn đang xem: Đọc ghi file trong android

Chú ý: Để rất có thể đọc/ghi trong tập tin lưu trong bộ nhớ ngoài, họ cần phân quyền vào tập tinAndroidManifest.xml
Các cách làm để lưu trữ dữ liệu
1.getExternalStorageState():Nên luôn kiểm tra tính sẵn sàng cho phép truy xuất của bộ nhớ lưu trữ ngoài thông qua hàmgetExternalStorageState()– trả về trạng thái lúc này của bộ lưu trữ ngoài. Vì bộ nhớ ngoài (thẻ nhớ, SDCard) rất có thể sẽ không có thể chấp nhận được các áp dụng trên trang bị truy xuất cho nó nếu vẫn ở chứng trạng tháo ra khỏi thiết bị hoặc đang được “mount” với 1 thiết bị khác ví như PC, máy vi tính chẳng hạn.
String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)) // External storage is available for read & write // TODO:if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) External storage is available lớn at least read // TODO:2. GetExternalFileDir(String type): Đối tượng tệp tin có đường dẫn thư mục nội bộ bên phía trong thư mục tài liệu của ứng dụng đặt trong bộ nhớ ngoài. Nếu bạn thông số truyền vào là Null, thì tác dụng trả về là thư mục gốc của thư mục dữ liệu của ứng dụng trong bộ nhớ lưu trữ ngoài.
// truy hỏi xuất folder pictures trong thư mục áp dụng trong bộ lưu trữ ngoài tệp tin file = new File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), "UserPrivatePicturesDirectory");if (!file.mkdirs()) Log.e("ITLog", "Directory not created");3. Environment.getExternalStoragePublicDirectory(): Đối tượng tệp tin có đường dẫn thư mục trong bộ lưu trữ ngoài dùng chung, vì mục đích chia sẻ, các tập tin này sẽ không biến thành xóa đi khi gỡ ứng dụng thoát khỏi thiết bị. Ví dụ như như, áp dụng bạn sử dụng camera để có thể chụp ảnh, và phần nhiều file hình ảnh này cần được giữ lại cho người dùng mặc dù ứng dụng của doanh nghiệp đã được gỡ ra khỏi thiết bị rồi.
// tróc nã xuất thư mục pictures trong bộ nhớ ngoài cần sử dụng chung.File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "UserPublicPicturesDirectory");if (!file.mkdirs()) Log.e("ITLog", "Directory not created");Phương thức trên thừa nhận đối số là chuỗi giá bán trị băng thông của thư mục nhỏ chứa những tập tin theo từng các loại (âm thanh, hình ảnh, tập tin dạng text, …) bên trong thư mục dữ liệu của ứng dụng. Phần nhiều giá trị băng thông này là những hằng quý giá được tư tưởng trong lớp Environment:
DIRECTORY_ALARMS — những file âm nhạc được dung có tác dụng báo thứcDIRECTORY_DCIM — Hình ảnh và clip được chụp hoặc quay bằng thiết bịDIRECTORY_DOWNLOADS — chứa những file được sở hữu vềDIRECTORY_MOVIES — chứa các file videoDIRECTORY_MUSIC — Chứa những file âm nhạc cho lịch trình nghe nhạcDIRECTORY_NOTIFICATIONS — những file âm thanh cho những thông đưa thông tin nhắnDIRECTORY_PICTURES — Chứa những file hình ảnhDIRECTORY_RINGTONES — các file music được dung có tác dụng nhạc chuôngBảng kết quả dưới đây điều khiển xe trên thiết bị mô phỏng.
Phương thức | Trả về |
getDataDirectory() | /data |
getDownloadCacheDirectory() | /cache |
getExternalStorageState() | mounted |
getExternalStoragePublicDirectory(Environment.Music): | /storage/emulated/0/Music |
getDownloadCacheDirectory() | /cache |
getRootDirectory() | /system |
Ví dụ:Trong ví dụ này bọn họ sẽ làm ứng dụng để lưu trữ dữ liệu trong bộ lưu trữ ngoài.Trong vận dụng có 2 Activity, Activity đầu tiên lưu trữ dữ liệu, Activity 2 dùng để đọc dữ liệu.Tiến hành tạo thành project, vào thư mục res /layout ->activity_main.xmlthiết kế giao diện sau:

Xem thêm: Tìm Hiểu Bài Hát Đang Phát Gần Bạn Là Gì, Piano Online
Bước 3:Trong tập tinstrings.xmlchúng ta định nghĩa những nhãn chotextview,edittextvàbutton.
Settings External Storage Example Back SHOW PRIVATE DATA SHOW PUBLIC DATA địa chỉ TEXT Click to View SAVE AS PRIVATE SAVE AS PUBLIC Main2Activity Hello world!Bước 4:Mởapp -> src ->MainActivity.javavà thêm code. Trong cách này họ mở MainActivity.java và thêm những phương thức mang lại 3button "SAVE AS PRIVATE","SAVE AS PUBLIC" và "Click to lớn View". Ởđây bọn họ xây dựng 2 phương thứcsavePrivate() vàsavePublic(), 2phương thức nàylấy tài liệu từedittextvà lưu giữ nó vào tập tin theo format là byte. Bọn họ cũng hiển thị đường dẫn tập tin thông qua đối tượngToast.Phương thức mang đến button "Click khổng lồ View" mở Activity 2.
package stockonmobile.com.externalstorage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import android.Manifest;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.support.v4.app.ActivityCompat;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity EditText editText; private int STORAGE_PERMISSION_CODE = 23;
Overrideprotected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);editText = (EditText) findViewById(R.id.editText2); public void next(View view) Intent intent = new Intent(MainActivity.this, Main2Activity.class); startActivity(intent); public void savePublic(View view) //Permission to lớn access external storage ActivityCompat.requestPermissions(this, new String<>Manifest.permission.READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE); String info = editText.getText().toString(); File thư mục = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);// thư mục Name file myFile = new File(folder, "myData1.txt");// Filename writeData(myFile, info); editText.setText(""); public void savePrivate(View view) String info = editText.getText().toString(); File thư mục = getExternalFilesDir("stockonmobile.com");// folder Name file myFile = new File(folder, "myData2.txt");// Filename writeData(myFile, info); editText.setText(""); private void writeData(File myFile, String data) FileOutputStream fileOutputStream = null; try fileOutputStream = new FileOutputStream(myFile); fileOutputStream.write(data.getBytes()); Toast.makeText(this, "Done" + myFile.getAbsolutePath(), Toast.LENGTH_SHORT).show(); catch (Exception e) e.printStackTrace(); finally if (fileOutputStream != null) try fileOutputStream.close(); catch (IOException e) e.printStackTrace(); Bước 5:Tạo thêmActivity Androidđặt tênMain2Activity .Mởres -> layout ->xml(hoặc) activity_main2.xmlvà thêm code:
Bước 6:Mở src -> package -> Main2Activity.java.Trong bước này chúng ta mở Main2Activity.java thêm các phương thức cho 3button "SHOWPRIVATE DATA","SAVE PUBLIC DATA" và "BACK". Ởđây họ xây dựng 2 phương thứcgetPrivate() vàgetPublic() lấy dữ liệu từ tập tinvà lưu lại nó vào đối tượng StringBuffer, tiếp đến hiển thị nó lêntextview.Phương thức đến button "Back" mở MainActivity.
package stockonmobile.com.externalstorage;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.TextView;public class Main2Activity extends Activity TextView showText;
Overrideprotected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);showText = (TextView) findViewById(R.id.getText); public void backMe(View view) Intent intent = new Intent(Main2Activity.this, MainActivity.class); startActivity(intent); public void getPublic(View view) File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS); // folder Name tệp tin myFile = new File(folder, "myData1.txt"); // Filename String text = getdata(myFile); if (text != null) showText.setText(text); else showText.setText("No Data"); public void getPrivate(View view) File thư mục = getExternalFilesDir("stockonmobile.com"); // folder Name file myFile = new File(folder, "myData2.txt"); // Filename String text = getdata(myFile); if (text != null) showText.setText(text); else showText.setText("No Data"); private String getdata(File myfile) FileInputStream fileInputStream = null; try fileInputStream = new FileInputStream(myfile); int i = -1; StringBuffer buffer = new StringBuffer(); while ((i = fileInputStream.read()) != -1) buffer.append((char) i); return buffer.toString(); catch (Exception e) e.printStackTrace(); finally if (fileInputStream != null) try fileInputStream.close(); catch (IOException e) e.printStackTrace(); return null; Download ví dụ
Ứng dụng này được cải tiến và phát triển bởiadt bundle,android 4.2sử dụngminimum sdk 8andtarget sdk 21.