Android實(shí)現(xiàn)文件存儲(chǔ)并讀取的示例代碼
要求:
輸入文件名,文件內(nèi)容分別存儲(chǔ)在手機(jī)內(nèi)存和外存中,并且都可以讀去取出來。
步驟:
1.創(chuàng)建一個(gè)名為CDsaveFile的Android項(xiàng)目
2.編寫布局文件activity_main.xml:
<LinearLayout 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" android:orientation="vertical" tools:context="hhh.exercise.cdsavefile.MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/textView_inputFileName" android:textColor="#00ff00" android:textSize="26sp" /> <EditText android:id="@+id/editView_fileName" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:hint="@string/editView_fileName" android:maxLines="1" android:textColor="#ff0000" android:textSize="26sp" /> <requestFocus /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/textView_inputFileContent" android:textColor="#00ff00" android:textSize="26sp" /> <EditText android:id="@+id/editView_fileContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:hint="@string/editView_fileContent" android:maxLines="2" android:minLines="2" android:textColor="#ff0000" android:textSize="26sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/button_saveToPhone" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/button_saveToPhone" android:textColor="#ff00ff" android:textSize="24sp" /> <Button android:id="@+id/button_readFromPhone" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/button_readFromPhone" android:textColor="#00ffff" android:textSize="24sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/button_saveToSD" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/button_saveToSD" android:textColor="#ff00ff" android:textSize="24sp" /> <Button android:id="@+id/button_readFromSD" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/button_readFromSD" android:textColor="#00ffff" android:textSize="24sp" /> </LinearLayout> <EditText android:id="@+id/editText_showResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:maxLines="3" android:minLines="3" android:hint="@string/editText_showResult" android:textColor="#cccc00" android:textSize="30sp" /> </LinearLayout>
3.編寫主活動(dòng)中代碼MainActivity.Java:
package hhh.exercise.cdsavefile;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import hhh.exercise.service.FileService;
public class MainActivity extends Activity implements OnClickListener {
private EditText editView_fileName;
private EditText editView_fileContent;
private EditText editText_showResult;
private FileService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// 實(shí)例化 FileService 類,該類用于處理按鈕觸發(fā)的事件的具體操作
service = new FileService(getApplicationContext());
// 獲取布局中的控件
editView_fileName = (EditText) findViewById(R.id.editView_fileName);
editView_fileContent = (EditText) findViewById(R.id.editView_fileContent);
editText_showResult = (EditText) findViewById(R.id.editText_showResult);
// 獲取按鈕并創(chuàng)建觸發(fā)事件
((Button) findViewById(R.id.button_saveToPhone)).setOnClickListener(this);
((Button) findViewById(R.id.button_readFromPhone)).setOnClickListener(this);
((Button) findViewById(R.id.button_saveToSD)).setOnClickListener(this);
((Button) findViewById(R.id.button_readFromSD)).setOnClickListener(this);
}
/**
* 為每一個(gè)按鈕創(chuàng)建觸發(fā)的事件
*
* @param v觸發(fā)事件的View對象
*/
@Override
public void onClick(View v) {
String fileName = editView_fileName.getText().toString();
String fileContent = editView_fileContent.getText().toString();
// 判斷文件名,文件名要求不為空
if (fileName == null || "".equals(fileName.trim())) {
Toast.makeText(getApplicationContext(), R.string.toast_missFileName, 0).show();
} else {
// 輸入的文件名不為空,對每個(gè)按鈕的觸發(fā)事件進(jìn)行處理
String result = null;
switch (v.getId()) {
case R.id.button_saveToPhone:
try {
// 存儲(chǔ)文件到手機(jī)上
service.saveToPhone(fileName, fileContent);
// 清空內(nèi)容輸入框
editView_fileContent.setText("");
Toast.makeText(getApplicationContext(), R.string.toast_saveToPhone_success, 0).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_saveToPhone_fail, 0).show();
e.printStackTrace();
}
break;
case R.id.button_readFromPhone:
try {
// 讀取手機(jī)文件中的內(nèi)容
result = service.readFromPhone(fileName);
// 將內(nèi)容顯示在空間中
editText_showResult.setText(result);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_readFromPhone_fail, 0).show();
e.printStackTrace();
}
break;
case R.id.button_saveToSD:
// 判斷sd卡是否存在,并且可以使用,空間足夠
int flag = judgeSD();
if (flag == 0 || flag == 1) {
Toast.makeText(getApplicationContext(), R.string.toast_noSD, 0).show();
} else {
try {
service.saveToSD(fileName, fileContent);
editView_fileContent.setText("");
Toast.makeText(getApplicationContext(), R.string.toast_saveToSD_success, 0).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_saveToSD_fail, 0).show();
e.printStackTrace();
}
}
break;
case R.id.button_readFromSD:
// 判斷SD卡能夠讀取
int flag2 = judgeSD();
if (flag2 != 0) {
try {
result = service.readFromSD(fileName);
editText_showResult.setText(result);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.toast_readFromSD_fail, 0).show();
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), R.string.toast_noSD, 0).show();
}
break;
default:
break;
}
}
}
/**
* 判斷SD卡是否存在,并且可以讀寫,空間足夠。
*
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private int judgeSD() {
int flag = 0;
// SD卡存在且可以讀取
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// 獲取SD卡的路勁
String path = Environment.getExternalStorageDirectory().getPath();
// 調(diào)用C的類庫
StatFs fs = new StatFs(path);
long availabeBolocks = 0;
long bolockSize = 0;
// 為了兼容低版本,所以獲取當(dāng)前應(yīng)用所在系統(tǒng)的版本號,進(jìn)而判斷
// 分為兩種。版本低于4.3的和高于等于4.3的(4.3的版本等級為18)
if (Build.VERSION.SDK_INT >= 18) {
// 獲取可用的塊
availabeBolocks = fs.getAvailableBlocksLong();
// 獲取每個(gè)塊的大小
bolockSize = fs.getBlockSizeLong();
} else {
// 獲取可用的塊
availabeBolocks = fs.getAvailableBlocks();
// 獲取每個(gè)塊的大小
bolockSize = fs.getBlockSize();
}
// 計(jì)算sd卡可用空間的大?。▎挝挥肕B)
long availableByte = availabeBolocks * bolockSize;
float availableMB = (float) availableByte / 1024 / 1024;
// 空間小于1MB,不允許寫入數(shù)據(jù)(實(shí)際上時(shí)空間小于寫入文件的大小,就不允許寫入,這里時(shí)認(rèn)為文件大小為1MB)
if (availableMB < 1) {
flag = 1;
} else {
flag = 2;
}
return flag;
} else {
return flag;
}
}
}
其中主活動(dòng)中FileService類是用來處理按鈕點(diǎn)擊后的事務(wù)的具體操作的。代碼如下:
package hhh.exercise.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.content.Context;
import android.os.Environment;
/**
* @author HHH
*
*/
public class FileService {
public Context context;
public FileService(Context context) {
super();
this.context = context;
}
/**
* 保存文件到手機(jī)內(nèi)存中
*
* @param fileName
* @param fileContent
* @return
* @throws Exception
*/
public void saveToPhone(String fileName, String fileContent) throws Exception {
OutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(fileContent);
bufferedWriter.close();
}
/**
* 從手機(jī)中讀取文件
*
* @param fileName
* @return
* @throws Exception
*/
public String readFromPhone(String fileName) throws Exception {
StringBuilder sBuilder = new StringBuilder();
InputStream inputStream = context.openFileInput(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sBuilder.append(line);
}
bufferedReader.close();
return sBuilder.toString();
}
/**
* 把輸入的內(nèi)容存入到SD卡中
*
* @param fileName
* @param fileContent
* @throws Exception
*/
public void saveToSD(String fileName, String fileContent) throws Exception {
// 獲取sd卡的路徑
String path = Environment.getExternalStorageDirectory().getPath();
File file = new File(path, fileName);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write(fileContent);
bufferedWriter.close();
}
/**
* 從sd卡中讀取文件
*
* @param fileContent
* @return
* @throws Exception
*/
public String readFromSD(String fileName) throws Exception {
StringBuilder sBuilder = new StringBuilder();
String path = Environment.getExternalStorageDirectory().getPath();
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(path, fileName)));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sBuilder.append(line);
}
bufferedReader.close();
return sBuilder.toString();
}
}
strings.xml的代碼如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">CDsaveFile</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="textView_inputFileName">請輸入文件名</string> <string name="editView_fileName">FileName</string> <string name="textView_inputFileContent">請輸入文件內(nèi)容</string> <string name="editView_fileContent">FileContent</string> <string name="button_saveToPhone">存到手機(jī)</string> <string name="button_saveToSD">存到SD卡</string> <string name="button_readFromPhone">讀取手機(jī)</string> <string name="button_readFromSD">讀取SD</string> <string name="editText_showResult">Here is the result of the reading</string> <string name="toast_missFileName">請輸入文件名,文件名不可為空</string> <string name="toast_saveToPhone_success">存儲(chǔ)到手機(jī)成功</string> <string name="toast_saveToPhone_fail">存儲(chǔ)到手機(jī)失敗啦......</string> <string name="toast_saveToSD_success">存儲(chǔ)到SD成功</string> <string name="toast_saveToSD_fail">存儲(chǔ)到SD失敗啦......</string> <string name="toast_noSD">sd不存在或空間不足</string> <string name="toast_readFromPhone_fail">無法讀取手機(jī)文件</string> <string name="toast_readFromSD_fail">無法讀取SD文件</string> </resources>
4.在AndroidManifest.xml添加權(quán)限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
5.項(xiàng)目部署在模擬器上:
進(jìn)入程序后:

把文件存儲(chǔ)到手機(jī)上并讀?。?

把文件存儲(chǔ)到SD上并讀?。?

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Android數(shù)據(jù)存儲(chǔ)之Android 6.0運(yùn)行時(shí)權(quán)限下文件存儲(chǔ)的思考
- android數(shù)據(jù)存儲(chǔ)之文件存儲(chǔ)方法
- android開發(fā)基礎(chǔ)教程—文件存儲(chǔ)功能實(shí)現(xiàn)
- Android圖片添加水印圖片并把圖片保存到文件存儲(chǔ)的實(shí)現(xiàn)代碼
- 實(shí)例詳解Android文件存儲(chǔ)數(shù)據(jù)方式
- 詳解Android開發(fā)數(shù)據(jù)持久化之文件存儲(chǔ)(附源碼)
- Android學(xué)習(xí)之文件存儲(chǔ)讀取
- 詳解Android文件存儲(chǔ)
- Android編程之SharedPreferences文件存儲(chǔ)操作實(shí)例分析
- Android開發(fā)文件存儲(chǔ)實(shí)例
相關(guān)文章
基于Android ContentProvider的總結(jié)詳解
本篇文章是對Android ContentProvider進(jìn)行了詳細(xì)的總結(jié)與分析,需要的朋友參考下2013-05-05
Android中使用CircleImageView和Cardview制作圓形頭像的方法
這篇文章主要介紹了Android中使用CircleImageView和Cardview制作圓形頭像的方法,簡單介紹了CircleImageView和Cardview的使用,需要的朋友可以參考下2016-09-09
Android 自定義SeekBar 實(shí)現(xiàn)分段顯示不同背景顏色的示例代碼
這篇文章主要介紹了Android 自定義SeekBar 實(shí)現(xiàn)分段顯示不同背景顏色,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
Android 第三方應(yīng)用接入微信平臺(tái)研究情況分享(二)
微信平臺(tái)開放后倒是挺火的,許多第三方應(yīng)用都想試下,這里把我的整個(gè)研究情況給出來,希望可以共同學(xué)習(xí),感興趣的朋友可以了解下2013-01-01
Android的權(quán)限設(shè)置及自啟動(dòng)設(shè)置方法
今天小編就為大家分享一篇Android的權(quán)限設(shè)置及自啟動(dòng)設(shè)置方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Android Studio設(shè)置或修改Android SDK路徑方法
在本篇文章中小編給大家整理了關(guān)于Android Studio設(shè)置或修改Android SDK路徑方法和相關(guān)知識點(diǎn),需要的朋友們學(xué)習(xí)下。2019-04-04
Android啟動(dòng)頁面定時(shí)跳轉(zhuǎn)的三種方法
這篇文章主要介紹了Android啟動(dòng)頁面定時(shí)跳轉(zhuǎn)的三種方法,實(shí)現(xiàn)打開一個(gè)Android手機(jī)APP的歡迎界面后跳轉(zhuǎn)到指定界面的效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
Android中使用socket使底層和framework通信的實(shí)現(xiàn)方法
native和framework的通信是通過jni,但是這一般只是framework調(diào)用native,native如果有消息要怎樣通知上層 呢?android中GSP模塊提供一種解決思路,但是實(shí)現(xiàn)有些復(fù)雜,這里介紹一種使用socket通信的方法可以使native和framework自由通信,感興趣的朋友一起看看吧2016-11-11

