TUT ANDROID 022: Đọc ghi file trong android
Trong bài này mình sẽ hướng dẫn các bạn cách đọc và ghi file trong android. Các bạn có thể đọc và ghi một file vào bộ nhớ trong và bộ nhớ ngoài trong android.
Để các bạn hiểu rõ phần này mình sẽ làm một ứng dụng đơn giản với các hàm đọc và ghi file trong android vào Internal Storage và External Storage ngoài ra các bạn cũng có thể đọc file từ một foder trong adroid.
Để làm được ví dụ này bạn làm lần lượt theo các bước sau
Bước 1: mở file AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.read_write_is" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.read_write_is.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Note: do chúng ta cần ghi ra bộ nhớ ngoài nên cần khai báo quyền
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
Bước 2: mở file res->layout-> layout_mainactivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/tvContentFile" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </RelativeLayout>
Bước 3 tạo class LogUtil.java trong packet com.example.read_write_is
package com.example.read_write_is; import android.util.Log; public class LogUtil { public static void LogD(String Tag, String Message) { Log.d(Tag, Message); } public static void LogE(String Tag, String Message) { Log.e(Tag, Message); } public static void LogI(String Tag, String Message) { Log.i(Tag, Message); } public static void LogW(String Tag, String Message) { Log.w(Tag, Message); } }
Bước 4 tạo foder res->raw
Copy 1 file .txt bất kỳ bạn muốn đọc nội dung trong ví dụ này mình copy file có tên cmd_find_log.txt
Bước 5: mở file MainActivity.java
package com.example.read_write_is; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.os.Bundle; import android.os.Environment; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private static final String FILENAME = "HighScore.txt"; private static final String ContentFile = "1. TruongBS 99999 \n2. LTT 88888"; private static final String FILENAME_ES = "DS.txt"; private TextView tvContentFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // ghi vao file co name FILENAME = "HighScore.txt" noi dung la ContentFile WriteToFile(FILENAME, ContentFile); tvContentFile = (TextView) findViewById(R.id.tvContentFile); // doc noi dung tu file co ten FILENAME va set gia tri cho textview tvContentFile.setText(ReadFromFile(FILENAME)); // copy 1 file bat ky trong thu muc res->raw trong vi du nay minh copy // file co ten la cmd_find_log // doc 1 file tu foder res->raw va hien thi toan bo file ra logcat LogUtil.LogD(TAG, ReadStaticfile(R.raw.cmd_find_log)); // ghi vao file co name FILENAME = "HighScore.txt" noi dung la ContentFile ra bo nho ngoai // de co the ghi ra bo nho ngoai ban can khai bao trong manifest // <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> // de co the thay duoc file trong the nho ban can khai bao dung luong trong SDcard cua may ao WriteToFileES(FILENAME, ContentFile); // doc 1 file tu bo nho ngoai co ten la FILENAME_ES = "DS.txt" // de chay duoc ham nay ban phai copy 1 file co name FILENAME_ES = "DS.txt" vao bo nho ngoai LogUtil.LogD(TAG, ReadFileFromES(FILENAME_ES)); } catch (Exception e) { // TODO: handle exception LogUtil.LogE(TAG, e.toString()); } } private String ReadFileFromES(String filenameEs) { // TODO Auto-generated method stub String result = null; try { // buoc 1 mo file FileInputStream fis = new FileInputStream( Environment.getExternalStorageDirectory() + "//" + filenameEs); // buoc 2 doc file int flength = fis.available(); if (flength != 0) { byte[] buffer = new byte[flength]; if (fis.read(buffer) != -1) { result = new String(buffer); } } // buoc 3 dong file fis.close(); } catch (Exception e) { // TODO: handle exception LogUtil.LogE(TAG, e.toString()); } return result; } private void WriteToFileES(String fname, String fcontent) { // TODO Auto-generated method stub try { // buoc 1 mo file de gi FileOutputStream fos = new FileOutputStream( Environment.getExternalStorageDirectory() + "//" + fname); // buoc 2 ghi noi dung vao file fos.write(fcontent.getBytes()); // buoc 3 dong file fos.close(); } catch (Exception e) { // TODO: handle exception LogUtil.LogE(TAG, e.toString()); } } private void WriteToFile(String filename2, String contentfile2) { // TODO Auto-generated method stub try { // buoc 1 mo file de gi FileOutputStream fos = openFileOutput(filename2, Context.MODE_PRIVATE); // buoc 2 ghi noi dung vao file fos.write(contentfile2.getBytes()); // buoc 3 dong file fos.close(); } catch (Exception e) { // TODO: handle exception LogUtil.LogE(TAG, e.toString()); } } private String ReadFromFile(String fName) { String result = null; try { // buoc 1 mo file FileInputStream fis = openFileInput(fName); // buoc 2 doc file int flength = fis.available(); if (flength != 0) { byte[] buffer = new byte[flength]; if (fis.read(buffer) != -1) { result = new String(buffer); } } // buoc 3 dong file fis.close(); } catch (Exception e) { // TODO: handle exception LogUtil.LogE(TAG, e.toString()); } return result; } private String ReadStaticfile(int rsID) { String result = null; try { Resources resources = getResources(); InputStream is = resources.openRawResource(rsID); // buoc 2 doc file int flength = is.available(); if (flength != 0) { byte[] buffer = new byte[flength]; if (is.read(buffer) != -1) { result = new String(buffer); } } } catch (Exception e) { // TODO: handle exception LogUtil.LogE(TAG, e.toString()); } return result; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Note:
Để thực hiện được ví dụ này các bạn cần tạo một máy ảo có cả bộ nhớ trong và bộ nhớ ngoài
Để đọc sử dụng được hàm ReadFileFromES
các bạn cần mở DDMS -> File Explorer -> “push a file onto the device”
lưu ý rằng bạn chỉ có thể vào DDMS và push file vào khi đã chạy máy ảo và máy ảo phải có SDCard
và chọn 1 file .txt bạn muốn đọc nội dung trong ví dụ này mình tạo 1 file đơn giản là DS.txt với mục đích mô tả việc đọc một file từ SDCard và ghi ra logcat
Các bạn có thể theo dõi kết quả thực hiện chương trình trên logcat và màn hình. Khi làm theo ví dụ các bạn có gì không hiểu có thể để lại câu hỏi trên web mình sẽ trả lời các bạn một cách nhanh nhất có thể. Các bạn có thể down full src theo link dưới đây
Kết quả thực hiện chương trình
Anh cho em hỏi về này xíu, em muốn lưu 1 image vào sdcard, hiện tại e đã lưu được. Em muốn hỏi anh là e muốn set thêm properties cho bức ảnh nữa thì phải làm sao, hiện tại e đang dùng ContentValues để insert vào theo đường dẫn file, nhưng như vậy chỉ xem được trên điện thoại, Khi em chép ra máy tính, xem phần detail bức ảnh thì không thấy properties này nữa. Anh có thể hướng dẫn giúp không ạ, Tks a!
bạn muốn lưu properties ntn bạn có thể nói rõ hơn k mình k hiểu bạn đang cần làm gì!
E đang làm 1 ứng dụng chụp hình và lưu lại vị trí người dùng và 1 số thông tin. A có thể hướng dẫn e ghi vào properties title và comment dc không. 2 properties này e xem trên window thì nó có tên là như vậy, không biết dưới code java phải code sao. chỉ cần lưu vào comment là dc rùi ạ, từ đó e có thể xử lý cắt ra theo ý muốn. Tks anh !
với ứng dụng như vậy bạn nên tạo 1 local DB SQLite ít nhất cần 1 bảng với các trường imageID, imageTitle, properties và link image… khi bận cần xử lý ảnh bạn có thể lấy ảnh lên và xử lý cũng như các thông tin của ảnh trong CSDL. nếu bạn có thể mô tả rõ hơn thì mình có thể cho bạn thêm 1 vài gợi ý
Vậy e xin nói rõ hơn về cái e đang làm ạ, e đang làm ứng dụng quản lý nhân viên. e cái này là 1 phần nhỏ trong đó. E muốn là nhân viên chụp các bức ảnh tại đâu đó và lưu lại trong máy cùng các thông tin lúc chụp như tọa độ GPS, ngày chụp,… Vào cuối ngày nhân viên này có thể dùng wifi để upload các bức ảnh này lên server. Trên server nhận dc bức ảnh và đọc properties từ bức ảnh. Ví dụ như GPS sau đó set lên bản đồ. Điều e muốn là thông tin của bức ảnh luôn đi kèm với bức ảnh đó, chứ không lưu riêng ra để khi upload chỉ cần upload bức ảnh. Anh có cách nào tối ưu support em với nhé, cách set properties không khả thi hả a. e Thấy các bức ảnh do phần mềm chụp ảnh của máy có thể set dc properties mà e không biết set theo dạng nào.
để e lưu thông tin của ảnh e nên tạo local db sqlite, khi gửi ảnh lên server e có thể gửi cả ảnh cả các thông tin cần thiết! e dùng multipart-form data để post ảnh và các thông tin cần thiết. Anh cũng chưa bao giờ thấy ai ghi properties của ảnh cả. Thông thường a hay lưu dạng DB và gửi lên server! Em thử làm theo hướng này xem.
oke, Tks anh nhiều, e sẽ thử hướng của anh
Chào anh, em cần hỏi em muốn up một file xml lên Cloud (cụ thể ở đây là Google Storage), và chương trình của em trên Android cần liên tục cập nhật đến file xml này (đọc, ghi và hiển thị). Em nên làm như thế nào ạ? Cảm ơn anh trước.
anh cũng chưa làm về phần này nhưng a có thể cho em một sô link tham khảo về nó nhé. e nên dùng api của google. em nên nghiên cứu theo hướng các link ở dưới đây nhé
http://stackoverflow.com/questions/17817288/uploading-file-into-google-cloud-mobile-backend
https://developers.google.com/datastore/docs/getstarted/start_java/
http://stackoverflow.com/questions/18002293/uploading-image-from-android-to-gcs
HI Anh,
E có một vài thắc mắc trong việc xử lý file cần anh giúp đỡ.
Em có 1 file đặt trong thư mục drawable. File này chứa thông tin về 10 sản phẩm (10 dòng) bao gồm: tên sản phẩm, mã sản phẩm, trạng thái (có hàng/ không có hàng)
Em có 1 activity đọc file này và hiển thị thông tin 10 sản phẩm lên màn hình. Người sử dụng có thể update lại trạng thái của sản phẩm (có hàng/ ko có hàng). Vậy làm thế nào để lưu lại trạng thái các sản phẩm sau khi đã được người sử dụng update lại?
Em có thể update trạng thái sản phẩm trực tiếp trên file trong drawable?
hay là em phải copy file từ drawable vào bộ nhớ trong Internal Storage và External Storage để xử lý?
Cảm ơn anh!