2012年9月17日 星期一
IO -- (4) SDCARD
IO: 列出SDCARD裡的夾子與檔案 & 讀取SDCARD裡某檔案的內容
public class IO_ListSDCardFilesActivity extends Activity {
/** Called when the activity is first created. */
private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
private final String FILE_NAME = "test02.txt";
private final String ENCODING = "UTF-8";
FileInputStream fis = null; // 這裡要設定,否則無法用
TextView tv;
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView);
//列出Sdcard 裡的夾子和檔案,放上LISTVIEW
try {
File sdcardPATH = Environment.getExternalStorageDirectory();// 找SD的入徑
String [] fileNamesArrayStr = sdcardPATH.list(); // 用list(),將SD裡的資料夾和檔案以字串的方式收集在array
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileNamesArrayStr);// 以 listView 顯示在螢幕上
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
readFile(); //讀出指定的檔到TEXTVIEW上
}// end of onCreate
public void readFile () {
String result = "";
try {
File mFilePath = new File (SD_PATH + FILE_PATH);
String mFileName = mFilePath + "/" + FILE_NAME;
File fileText = new File (mFileName);
fis = new FileInputStream(fileText);
int length = fis.available();
byte [] buffer = new byte [length];
fis.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
fis.close();
tv.setText(result);
} catch (Exception e) {
e.printStackTrace();
}
}// end of readFile();
}
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言