文件存取編程基礎

文件

   1. 文件可以用來存儲比使用引用更大數量的數據
   2. Android 提供方法來讀、寫文件
   3. 只有本地文件可以被訪問
   4. 優點:可以存儲大容量的數據
   5. 缺點:文件更新或是格式改變可能會導致巨大的編程工作

文件操作
## 讀文件 ##
Context.openFileInput(String name)打開一個與應用程序聯繫的私有文件輸入流
當文件不存在時拋出FileNotFoundException 異常

FileInputStream in = this.openFileInput("test2.txt");//打開文件"test2.txt"
……
in.close();//關閉輸入流

`## 寫文件 ##“
Context.openFileOutput(String name,int mode)開啓一個與應用程序聯繫的私有文件輸出流
當文件不存在時該文件將被創建
文件輸出流可以在添加模式中打開,這意味新的數據將被添加到文件的末尾

FileOutputStream out = this.openFileOutput(“test2.txt”,MODE_APPEND);
//打開文件”test2.txt”進行寫操作、使用MODE_APPEND 在添加模式中打開文件
……
out.close();//關閉輸出流

**讀取靜態文件**
      要打開打包在應用程序中的靜態文件,使用Resources.openRawResource(R.raw.mydatafile)
      該文件必須放在文件夾res/raw/中
      ![這裏寫圖片描述](http://img.blog.csdn.net/20160621153148472)

InputStreamin = this.getResources().openRawResource(R.raw.my);
… //獲得Context資源
in.close();//關閉輸入流

**文件存取示例**
創建添加文件內容並保存,打開文件並顯示內容
① 新建工程FileWriteRead
② 修改main.xml 佈局,添加一個EditText、一個Button

③ 在res/layout 中新建一個open.xml 佈局文件,添加一個TextView、兩個Button("打開","清空")

④ 文件存儲

/定義IO對象/
private String Text_of_input;
private OutputStream os;
Text_of_input = inputArt.getText().toString();
//得到用戶輸入字符
try {
os = this.openFileOutput(“txtME”, MODE_PRIVATE);
//打開一個文件輸出流。名稱爲txtME,模式爲不覆蓋
os.write(Text_of_input.getBytes());
//把內容寫入文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} finally {
try {
//關閉文件輸出流
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

⑤ 文件讀取

/定義IO對象/
private String Text_of_output;
private InputStream is;
private byte[] b;
try {
//打開一個文件輸入流。名稱爲txtME
is = this.openFileInput(“txtME”);
//字節數組聲明定義
b = new byte[1024];
//讀取文件內容放入字節數組
int length = is.read(b);
//把字節數組轉換成字符串
Text_of_output = new String(b);
//顯示讀取內容長度
setTitle(“文件字數:” + length);
//顯示讀取的文件內容
showmyText.setText(Text_of_output);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}finally {
try {
//關閉文件輸入流
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

⑥ 修改mianActivity.java 文件,添加menu 菜單與操作

package zyf.FileWrite;
/導入要使用的包/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class FileWrite extends Activity implements Button.OnClickListener {
/* Called when the activity is first created. /
/要使用的對象、變量聲明/
/保存部分/
private EditText inputArt;/編輯框,輸入用戶字符串/
private Button saveButton;/按鈕,保存/
private String Text_of_input;/字符串,用戶輸入的字符串/
private OutputStream os;/文件輸出流,保存文件流/
/讀取部分/
private TextView showmyText;/TextView,顯示讀取文件內容/
private Button openTxt,cleanTxt;/按鈕,打開文件/
private String Text_of_output;/字符串,從文件中讀取到得 字符串/
private InputStream is;/文件輸入流,讀取文件流/
private byte[] b;/字節數組,用來讀取文件內容/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLayoutShow(R.layout.main);/設置主屏佈局/
UIinit(“main”);/初始化UI元素方法/
Logic(“main”);/添加事件邏輯方法/
} /*設



*/
private void setLayoutShow(int layoutID) {
// TODO Auto-generated method stub
setContentView(layoutID);/設置當前主屏佈局/
} private void UIinit(String mainROopen) {
/初始化UI/
if (mainROopen.equals(“main”)) {
inputArt = (EditText) findViewById(R.id.EditText_Txt);
saveButton = (Button) findViewById(R.id.Button_Save);
} else if (mainROopen.equals(“open”)) {
showmyText = (TextView) findViewById(R.id.TextView_showTxt);
openTxt = (Button) findViewById(R.id.Button_openTxt);
cleanTxt=(Button)findViewById(R.id.Button_clean);
}
} private void Logic(String string) {
// TODO Auto-generated method stub
/爲按鈕添加事件處理/
if (string.equals(“main”)) {
saveButton.setOnClickListener(this);
} else if (string.equals(“open”)) {
openTxt.setOnClickListener(this);
cleanTxt.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
/根據ID判斷按鈕事件/
switch (v.getId()) {
case R.id.Button_Save: {
/提示/
NoteDebug(“文件保存”);
// TODO Auto-generated method stub
/獲得用戶輸入的字符串/
Text_of_input = inputArt.getText().toString();
try {
/打開文件輸出流,名稱txtME,以不覆蓋模式打開/
os = this.openFileOutput(“txtME”, MODE_PRIVATE);
/把字符串轉換成字節數組,寫入文件中/
os.write(Text_of_input.getBytes());
} catch (FileNotFoundException e) {
/文件未找到,異常/
// TODO Auto-generated catch block
NoteDebug(“文件關閉失敗” + e);
} catch (IOException e) {
/文件寫入錯誤/
// TODO Auto-generated catch block
NoteDebug(“文件寫入失敗” + e);
} finally {
try {
/關閉文件輸出流/
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
NoteDebug(“文件關閉失敗” + e);
}
} /*輸




*/
inputArt.setText(“”);
}
break;
case R.id.Button_openTxt: {
NoteDebug(“文件打開”);
try {
/打開文件輸入流,名稱txtME/
is = this.openFileInput(“txtME”);
/初始化字節數組/
b = new byte[1024];
/從文件輸入流中讀取內容到字節數組中,返回內容長度/
int length = is.read(b);
/把字節數組轉換成字符串/
Text_of_output = new String(b);
/設置標題,顯示文件內容長度/
setTitle(“文件字數:” + length);
/顯示文件內容/
showmyText.setText(Text_of_output);
} catch (FileNotFoundException e) {
/文件未找到,異常/
// TODO Auto-generated catch block
NoteDebug(“文件打開失敗” + e);
} catch (IOException e) {
/文件讀取錯誤,異常/
// TODO Auto-generated catch block
NoteDebug(“文件讀取失敗” + e);
}
finally {
try {
/關閉文件輸入流/
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
NoteDebug( “文件關閉失敗”+e);
}
}
}
break;
case R.id.Button_clean:{
/清空/
showmyText.setText(“”);
NoteDebug(“清空”);
}
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
/添加三個菜單項目,並設置圖片/
menu.add(0, 1, 1, “Edit”).setIcon(R.drawable.ic_menu_edit);
menu.add(0, 2, 2, “Open”).setIcon(R.drawable.ic_menu_agenda);
menu.add(0, 3, 3, “Exit”).setIcon(R.drawable.ic_lock_power_off);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case 1:
/顯示main.xml爲主屏佈局/
setLayoutShow(R.layout.main);
UIinit(“main”);
Logic(“main”);
NoteDebug(“編輯文件Layout”);
break;
case 2:
/顯示open.xml爲主屏佈局/
setLayoutShow(R.layout.open);
UIinit(“open”);
Logic(“open”);
NoteDebug( “打開文件Layout”);
break;
case 3:
/退出/
finish();
NoteDebug( “Byebye”);
break;
default:
break;
} return super.onOptionsItemSelected(item);
} private void NoteDebug(String showString){
/顯示Toast提示/
Toast.makeText(this,showString, Toast.LENGTH_SHORT).show();
}
}
“`
⑦ 結果
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

發佈了37 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章