通過 Windows 命令提示符(cmd)在桌面新建文件夾,并在該文件夾中編譯、運行一段 Java 程序段
983
2025-03-31
Android 數據存儲
1訪問資源文件
直接將文件保存在設備的內部存儲. 默認情況下,保存到內部存儲的文件為私有的,其他應用程序不能訪問它們,當用戶卸載應用程序時,所保存的文件也一并刪除。
1.1訪問靜態應用程序文件-只讀
1.1.1從resource中的res/raw文件夾中獲取文件
保存靜態文件, 通過openRawResource()傳入資源ID( R.raw.
示例:
String res = "";
try{
InputStream in = getResources().openRawResource(R.raw.bbi);
//在\Test\res\raw\bbi.txt,
int length = in.available();
byte [] buffer = new byte[length];
in.read(buffer);
//res = EncodingUtils.getString(buffer, "UTF-8");
//res = EncodingUtils.getString(buffer, "UNICODE");
res = EncodingUtils.getString(buffer, "BIG5");
//依bbi.txt的編碼類型選擇合適的編碼,如果不調整會亂碼
in.close();
}catch(Exception e){
e.printStackTrace();
}
//把得到的內容顯示在TextView上
myTextView.setText(res);
1.1.2從asset中獲取文件并讀取數據(資源文件只能讀不能寫)
assets目錄下,稱為原生文件,這類文件在被打包成apk文件時是不會進行壓縮的,android使用AssetManager對assets文件進行訪問,通過getResources().getAssets()獲得AssetManager,
其有一個open()方法可以根據用戶提供的文件名,返回一個InputStream對象供用戶使用。
eg:
//文件名字
String fileName = "yan.txt";
String res="";
try{
// \Test\assets\yan.txt這里有這樣的文件存在
//通過getResources().getAssets()獲得AssetManager
InputStream in = getResources().getAssets().open(fileName);
//返回讀取的大概字節數
int length = in.available();
byte [] buffer = new byte[length];
in.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
1.2訪問設備存儲相當于API工作目錄
1.2.1調用context.openFileInput() 返回 FileInputStream讀文件
1.2.2通過調用context.openFileOutput() 返回FileOutputStream寫文件
//寫文件在./data/data/com.tt/files/下面
openFileOutput()參數
filename 文件名
int mode 操作模式 MODE_PRIVATE 默認,創建或替換該文件名的文件作為應用程序私有文件。
MODE_APPEND,MODE_WORLD_READABLE , MODE_WORLD_WRITEABLE,
eg:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
1.3保存緩存文件
如果您想緩存一些數據,而不是它長期存放,可以把文件保存為緩存文件;保存為緩存文件時,當設備內部存儲空間不足,系統可能會刪除這些緩存文件恢復空間;我們應該限制緩存空間的大小;
當用戶卸載應用程序時,這些文件將被刪除。
使用方法:
//獲取保存文件系統的目錄絕對路徑
getFilesDir();
//在存儲空間中創建或打開一個目錄
getDir();
//刪除存儲文件
deleteFile();
//返回應用程序保存文件列表
fileList();
2使用外部存儲
2.1.1檢測外部存儲狀態:
Environment.getExternalStorageState()
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;
}
2.1.2訪問外部存儲
API8以上,使用getExternalFilesDir()打開一個外部存儲文件目錄,這個方法需傳遞一個指定類型目錄的參數,如:DIRECTORY_MUSIC和DIRECTORY_RINGTONES,為空返回應用程序文件根目錄;
此方法可以根據指定的目錄類型創建目錄,該文件為應用程序私有,如果卸載應用程序,目錄將會一起刪除。
API7一下,使用getExternalStorageDirectory(), 打開外部存儲文件根目錄 ,你的文件寫入到如下目錄中:/Android/data/
eg:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. ?Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). ?Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
file.delete();
}
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. ?If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
return file.exists();
}
return false;
}
2.1.3保存為共享文件
如果想將文件保存為不為應用程序私有,在應用程序卸載時不被刪除,需要將文件保存到外部存儲的公共目錄上,這些目錄在存儲設備根目錄下;如:音樂,圖片,鈴聲等。
API8以上,使用 getExternalStoragePublicDirectory(),傳入一個公共目錄的類型參數,如DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES等, 目錄不存在時這個方法會為你創建目錄。
API7一下,使用 getExternalStorageDirectory() 打開存儲文件根目錄,保存文件到下面的目錄中:
Music,Podcasts,Ringtones,Alarms,Notifications,Pictures,Movies,Download。
eg:
void createExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user's public pictures directory.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user's
// public pictures directory and delete the file. ?If external
// storage is not currently mounted this will fail.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
file.delete();
}
boolean hasExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user's
// public pictures directory and check if the file exists. ?If
// external storage is not currently mounted this will think the
// picture doesn't exist.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
return file.exists();
}
2.1.4保存緩存文件
API8以上,使用getExternalCacheDir() 打開存儲目錄保存文件,如卸載應用程序,緩存文件將自動刪除,在應用程序運行期間你可以管理這些緩存文件,如不在使用可以刪除以釋放空間。
API7以下,使用getExternalStorageDirectory() 打開緩存目錄,緩存文件保存在下面的目錄中:
/Android/data/
2.1.5讀寫文件
提示:openFileOutput是在raw里編譯過的訪問設備存儲,FileOutputStream是任何文件都可以
訪問sdcard直接實例FileOutputStream對象,而訪問存儲設備文件通過openFileOutput返回FileOutputStream對象對數據操作。
2.1.6 sdcard中去讀文件
示例:
String fileName = "/sdcard/Y.txt";
//也可以用String fileName = "mnt/sdcard/Y.txt";
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
//FileInputStream fin = openFileInput(fileName);
//用這個就不行了,必須用FileInputStream
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}catch(Exception e){
e.printStackTrace();
}
myTextView.setText(res);
2.1.7 SDCard中寫文件
般寫在\data\data\com.test\files\里面,打開DDMS查看file explorer是可以看到仿真器文件存放目錄的結構的
String fileName = "TEST.txt";
String message = "FFFFFFF11111FFFFF" ;
writeFileData(fileName, message);
public voidwriteFileData(String fileName,String message){
try{
FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
byte [] bytes = message.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
2.1.8 寫,讀sdcard目錄上的文件,要用FileOutputStream, 不能用openFileOutput
//寫在/mnt/sdcard/目錄下面的文件
public voidwriteFileSdcard(String fileName,String message){
try{
//FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
FileOutputStream fout = new FileOutputStream(fileName);
byte [] bytes = message.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//讀在/mnt/sdcard/目錄下面的文件
public String readFileSdcard(String fileName){
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
3android讀寫文件正確實行方法
Android讀寫文件正確實行方法介紹
http://www.ehuait.com/skill/android/2011-09-08/1445.html
眾所周知Android有一套自己的安全模型, 具體可參見Android開發文檔。當應用程序(.apk)在安裝時就會分配一個userid,當該應用要去訪問其他資源比如文件的時候,就需要userid匹配。
默認情況下,任何應用創建的文件,數據庫,sharedpreferences都應該是私有的(位于/data/data/your_project/files/),其余程序無法訪問。
除非在創建時指明是MODE_WORLD_READABLE 或者 MODE_WORLD_WRITEABLE,只要這樣其余程序才能正確訪問。
因為有這種Android讀寫文件的方法在安全上有所保障,進程打開文件時Android要求檢查進程的user id。所以不能直接用java的api來打開,因為java的io函數沒有提這個機制 。
無法用java的api直接打開程序私有的數據 ,默認路徑為/data/data/your_project/files/
1.FileReader file = new FileReader("Android.txt"); 這里特別強調私有數據!言外之意是如果某個文件或者數據不是程序私有的,即訪問它時無須經過Android的權限檢查,那么還是可以用java的io api來直接訪問的。
所謂的非私有數據是只放在sdcard上的文件或者數據,可以用java的io api來直接打開sdcard上文件。
1.FileReader file = new FileReader("/sdcard/Android.txt"); 如果要打開程序自己私有的文件和數據,那必須使用Activity提供openFileOutput和openFileInput方法。
創建程序私有的文件,由于權限方面的要求,必須使用activity提供的Android讀寫文件方法
1.FileOutputStream os = this.openFileOutput("Android.txt", MODE_PRIVATE);
2.OutputStreamWriter outWriter = new OutputStreamWriter (os);
讀取程序私有的文件,由于權限方面的要求,必須使用activity提供的方法
1.FileInputStream os =this.openFileInput("Android.txt");
2.InputStreamReader inReader = new InputStreamReader(os);
4Shared Preferences用戶首選項
主要用于存放軟件的配置參數等信息。sharedPreferences用于存取和修改軟件配置參數數據的接口。存放鍵值對,保存用戶個人首選項信息,比如喜愛音樂,主題,首選Activity等
4.1.1使用getSharedPrefernces()
使用步驟:
存放:
1.獲得SharedPreferences 的實例對象,通過getSharedPreferences()傳遞文件名和模式;
2.獲得Editor 的實例對象,通過SharedPreferences 的實例對象的edit()方法;
3.存入數據,利用Editor 對象的putXXX()方法;
4.提交修改的數據,利用Editor 對象的commit()方法。
讀取:
1.獲得SharedPreferences 的實例對象,通過getSharedPreferences()傳遞文件名和模式;
2.讀取數據,通過SharedPreferences 的實例對象的getXXX()方法。
eg:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
4.1.2 getPreferences()
Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
Android
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。