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();
}
IO: (6) + TTS 給英聽練習使用
IO + TTS : 給英聽練習使用
主程式:
//設計英語英聽口說練習
public class IO_TTS_EnglishSpeakingActivity extends Activity implements OnInitListener{
/** Called when the activity is first created. */
private final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
// private final String ENCODING = "UTF-8";
private File [] filesArray;
private File mDataPath;
private FileInputStream fis = null;
TextView tv;
ListView lv;
private String aFileName;
String [] strings;
private TextToSpeech mTTS;
private Button answerBtn;
private Button goBackBtn;
String result = "";
private static int NO_OF_QUESTIONS = 5;
private String [] questionsStr = new String [NO_OF_QUESTIONS];
private int flag; //判斷是否還留在原來的試卷裡
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv= (TextView) findViewById(R.id.textView01);
// tv.setMovementMethod(ScrollingMovementMethod.getInstance());
mDataPath = new File (SDCARD_PATH + FILE_PATH);
filesArray = mDataPath.listFiles();
listFiles();//列出所有的檔案
mTTS = new TextToSpeech(getApplicationContext(), this);//初始化
answerBtn = (Button) findViewById(R.id.button2);
answerBtn.setOnClickListener(answerListener);
goBackBtn = (Button) findViewById(R.id.goBackButton);
goBackBtn.setOnClickListener (goBackListener);
flag = 1;
}// end of onCreate
//列出所有英聽的檔案,顯示在ListView上
private void listFiles() {
String fileNames = ""; // to receive every single file name
for (int i = 0; i < filesArray.length; i++) {
if (filesArray[i].isFile()) { //get rid of directories
String tempStr = ""; //會多出入徑的字串
tempStr = filesArray[i].toString();
String strSub = ""; //to subtract the uneccessary part: /mnt/sdcard/fileio/ (19 個字元)
strSub = tempStr.substring(19, tempStr.length()).toString();
fileNames += strSub + "--";
}
}
//Handle to subtraction of the final "--" in fileNames string
String result = "";
result = fileNames.substring(0, fileNames.length()-2);
strings = TextUtils.split(result, "--");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
lv.setOnItemClickListener(listener);
}// end of listFiles ();
// 看答案的按鈕
private OnClickListener answerListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (questionsStr[0] == null) {
Toast.makeText(Cq_IO01Activity.this, "請選擇試卷!",
Toast.LENGTH_SHORT).show();
tv.setMarqueeRepeatLimit(-1);
} else if (flag == 1){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
Cq_IO01Activity.this,
android.R.layout.simple_list_item_1, questionsStr);
lv.setAdapter(adapter);
answerBtn.setText("不看題目");
answerBtn.setTextColor(Color.MAGENTA);
flag = 0;
} else if (flag == 0) {
listFiles();
answerBtn.setText("觀看題目");
answerBtn.setTextColor(Color.BLACK);
flag = 1;
}
}
};
//按下按鈕回到原先列出全部英聽檔案的畫面
private OnClickListener goBackListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mTTS != null) {
mTTS.stop();
}
listFiles();
tv.setText("請選擇下列試題卷練習英聽口說:");
tv.setTextColor(Color.RED);
tv.setMarqueeRepeatLimit(-1);
answerBtn.setText("觀看題目");
answerBtn.setTextColor(Color.BLACK);
}
};
//選擇要唸出的檔案; 將內容的五個問題分別間隔唸出
private OnItemClickListener listener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
aFileName = strings[position].toString();
tv.setText("正在播放 " + aFileName + " 練習,一共五題,每題播放兩次:");
tv.setTextColor(Color.GREEN);
tv.setMarqueeRepeatLimit(-1);
readSingleLine(aFileName); //讀出每個問題
}
};// end of listener
private void readSingleLine (String aFileName) {
try {
String mFileName = mDataPath + "/" + aFileName;
File fileContent = new File (mFileName);
fis = new FileInputStream(fileContent);
DataInputStream dis = new DataInputStream(fis);
for (int i = 0; i< NO_OF_QUESTIONS; i++) {
String tempStr = "";
tempStr = dis.readLine() + "\n";
questionsStr[i] = tempStr;
//讀出所選檔案的內容
mTTS.speak(tempStr, TextToSpeech.QUEUE_ADD, null); //用QUEUE_ADD可以再接其他的字串;queue_flush將無法做到 //唸第一次
mTTS.playSilence(2000, TextToSpeech.QUEUE_ADD, null); //停頓兩秒
mTTS.speak(tempStr, TextToSpeech.QUEUE_ADD, null); //唸第二次
mTTS.playSilence(2000, TextToSpeech.QUEUE_ADD, null); //停頓兩秒
mTTS.speak("Please answer now.", TextToSpeech.QUEUE_ADD, null); //請使用者回答
mTTS.playSilence(8000, TextToSpeech.QUEUE_ADD, null); //給予八秒的時間回答
}
} catch (Exception e) {
e.printStackTrace();
}
}// end of readSingleLine ()
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
mTTS.setSpeechRate(0.9f);// 正常速度是 1.0f; 小過它會變慢
mTTS.speak("I'm ready for listening and speaking practice.", TextToSpeech.QUEUE_FLUSH, null);
}else {
System.out.println("Oops!");
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mTTS.shutdown();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mTTS != null) {
mTTS.stop();
}
}
}
**********************************
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/sunset" >
<TextView
android:id="@+id/textView01"
android:layout_width="350px"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:text="請選擇下列試題卷練習英聽口說:"
android:ellipsize="marquee"
android:scrollHorizontally="true"
android:singleLine="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:textColor="#FF0000"
android:textSize="22dp" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_weight="0.70"
android:divider="@drawable/list_item_divider"
android:cacheColorHint="#00FF0000"
android:dividerHeight="5px" >
</ListView>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button2"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="觀看題目" />
<Button
android:id="@+id/goBackButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="選擇新試卷" />
</LinearLayout>
</LinearLayout>
*******************************
res/drawable/list_item_divider:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<stroke
android:width="1dp"
android:color="#8F8F8F"
android:dashWidth="1dp"
android:dashGap="1dp"/>
</shape>
2012年8月17日 星期五
IO --(5)讀出的檔案內容,套用TTS,將內容以機器合成聲音讀出
IO --(5)讀出的檔案內容,套用TTS,將內容以機器合成聲音讀出
設計讓練習英聽的學生使用
Manifest.xml:
加上:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
***********************
main.java: 主程式
public class IO_TTSActivity extends Activity implements OnInitListener{
/** Called when the activity is first created. */
private final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
// private final String FILE_NAME = "test03.txt";
private final String ENCODING = "UTF-8";
private File mDataPath;
private FileInputStream fis = null;
TextView tv;
ListView lv;
String [] strings;
private TextToSpeech mTTS;
private Button listenBtn;
String result = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv= (TextView) findViewById(R.id.textView01);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());
mDataPath = new File (SDCARD_PATH + FILE_PATH);
File [] filesArray = mDataPath.listFiles();
String fileNames = ""; // to receive every single file name
for (int i = 0; i < filesArray.length; i++) {
if (filesArray[i].isFile()) { //get rid of directories
String tempStr = ""; //會多出入境的字串
tempStr = filesArray[i].toString();
String strSub = ""; //to subtract the uneccessary part: /mnt/sdcard/fileio/ (19 個字元)
strSub = tempStr.substring(19, tempStr.length()).toString();
fileNames += strSub + "--";
}
}
//Handle to subtraction of the final "--" in fileNames string
String result = "";
result = fileNames.substring(0, fileNames.length()-2);
strings = TextUtils.split(result, "--");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
lv.setOnItemClickListener(listener);
mTTS = new TextToSpeech(getApplicationContext(), this);//初始化
listenBtn = (Button) findViewById(R.id.button1);
listenBtn.setOnClickListener(btnListener);
}// end of onCreate
//選擇要唸出的檔案
private OnItemClickListener listener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
tv.setText(""); // clean tv in case of left-over
String aFileName = strings[position].toString();
readFile(aFileName);//Method: read the content of a file
//讀出所選檔案的內容;用QUEUE_ADD可以再接其他的字串;QUEUE_FLUSH將無法做到
mTTS.speak(result, TextToSpeech.QUEUE_ADD, null);
mTTS.playSilence(5000, TextToSpeech.QUEUE_ADD, null); //休息五秒
mTTS.speak(result, TextToSpeech.QUEUE_ADD, null); //又重複將內容朗誦一遍
}
};// end of listener
//看答案的按鈕
private OnClickListener btnListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText(result);
}
};
//讀出檔案的內容
private void readFile(String aFileName) {
try {
String mFileName = mDataPath + "/" + aFileName;
File fileContent = new File (mFileName);
fis = new FileInputStream(fileContent);
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()
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
mTTS.speak("I'm ready", TextToSpeech.QUEUE_FLUSH, null);
}else {
System.out.println("Oops!");
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mTTS.shutdown();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mTTS != null) {
mTTS.stop();
}
}
}
****************************************
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="#FF0000"
android:textSize="20dp"
android:text="選擇下列檔案練習英聽:" />
<TextView
android:id="@+id/textView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:maxLines="15"
android:scrollbarStyle="outsideInset"
android:scrollbars="vertical"
android:singleLine="false"
android:text=""
android:textColor="#00FF00"
android:textSize="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="看答案!" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_weight="0.85" >
</ListView>
</LinearLayout>
2012年7月17日 星期二
IO: (2) SDCARD
IO: (2) 僅列出SDCARD裡檔案的名稱(不包括資料夾)
public class OnlyFileNamesInSDCardActivity 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);
//列出Sdcard 裡的夾子和檔案,放上LISTVIEW
try {
//找出SD的入徑
File sdcardPATH = Environment.getExternalStorageDirectory();
//用list(),將SD裡的資料夾和檔案以字串的方式收集在array
// String [] fileNamesArrayStr = sdcardPATH.list();
//listFiles()則會加上完整入徑,列出入徑及資料夾+檔名的集合,存在File格是的陣列
File [] fileArray = sdcardPATH.listFiles();
/*** 如果要制訂特別的入徑 ***/
// File myDataPath = new File (sdcardPATH.getAbsolutePath() + "/fileio");
// File [] fileArray = myDataPath.listFiles(); //不要忘了要計算、減掉入徑的字元數
String tempStr = ""; //初始化
for (int i=0; i < fileArray.length; i++) {//只收集檔案,不要資料夾,但每筆資料會產生入徑(但無法用 fileNamesArrayStr來做,因為它是字串,無法判定是否為檔案還是資料夾
if (fileArray[i].isFile()) {
//用來接收每一筆的檔案名字串,但是會包含前面的入徑:/mnt/sdcard/
String str = "";
str = fileArray[i].toString();
// 用來去除多餘的入徑字串:/mnt/sdcard/
String strSub = "";
//利用substring 去掉每筆最前面的12個字元:/mnt/sdcard/
strSub = str.substring(12, str.length()).toString();
// 以 "--"為記號,分隔每筆處理好的資料,存成一筆字串
tempStr += "--" + strSub;
}
}
//設一變數來處理最後的"--"兩個字元,讓它不會在ListView上多產生一個空的cell
String result = "";
Result = tempStr.substring(0, tempStr.length()-2);
//以"--"為分節點將整筆字串切割成數個字串儲存成字串陣列,以顯示在螢幕上
String[] strings = TextUtils.split(reselt, "--");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}// end of onCreate
}
2012年5月31日 星期四
網路檔案下載─FTP
網路檔案下載─FTP: 從中華電信提供的網路存放空間,下載檔案。
使用外部元件: Apache Commons NET
commons-net-3.0.1-src.zip 的class : 下載點
1. Unzip it.
2. 到Eclipse的android作業平台上的 File -> Import -> General -> File System
3. 然後 Browse 剛才Unzip後 存放 commons-net-3.0.1-src 的夾子,找到 java 的子目錄,然後按『確定』。
需開啟之權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
main.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class FTPDownloadFileActivity extends Activity {
/** Called when the activity is first created. */
private TextView tv;
private TextView tvContent;
private String fileName = "myFile.txt"; //網站上準備要下載的檔名
private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/download";
private final String FILE_NAME = "copy_" + fileName; //下載進手機後的檔名
private final String ENCODING = "UTF-8";
private FileInputStream fis = null;
private ProgressDialog mProgressDialog;
private Handler handler = new Handler(){ //使用handler, thread 防止下載檔案太大
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
mProgressDialog.dismiss(); //close
readFile();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.textview);
tvContent = (TextView) findViewById(R.id.textviewContent);
processThread();
}
private void ftpDownload() { //使用FTP 下載檔案
FTPClient ftpClient = new FTPClient();
try {
// ftpClient.connect(InetAddress.getByName("203.66.87.21"));//與以下的String 意義一樣
ftpClient.connect(InetAddress.getByName("ftp.myweb.hinet.net")); //中華電信的網頁IP ADDRESS
ftpClient.login("username", "password");
tv.setText(String.valueOf(ftpClient.isConnected()));
ftpClient.changeWorkingDirectory("/");
File localfile = new File ("/sdcard/download/" + FILE_NAME);
OutputStream os = new FileOutputStream(localfile);
ftpClient.enterLocalPassiveMode();
ftpClient.retrieveFile(fileName, os);
ftpClient.logout();
ftpClient.disconnect();
}catch (Exception e) {
e.printStackTrace();
}
}
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();
tvContent.setText(result);
} catch (Exception e) {
e.printStackTrace();
}
}
private void processThread() {
mProgressDialog = ProgressDialog.show(this, "文件下載", "正在下載...");
new Thread () {
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
ftpDownload();
prolongedActionMethod(); //做測試用的
handler.sendEmptyMessage(0);
}
}.start();
}
private void prolongedActionMethod() { //故意延遲十秒鐘,做測試用的
try {
Thread.sleep(10000);
}catch (Exception e){
e.printStackTrace();
}
}
}
*************************************************
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<!-- 將 TextView 包在 ScrollView 裡,當內容太長,可以捲動。 -->
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadingEdge="vertical"
android:paddingTop="10dip"
android:scrollbars="vertical" >
<TextView
android:id="@+id/textviewContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="10dip"
android:text=""
android:textSize="20dp"
android:textColor="#00FF00" />
</ScrollView>
</LinearLayout>
2012年5月4日 星期五
IO: (3) 讀取SDCARD/fileio裡某個檔案的內容
IO
//讀取SDCARD/fileio裡檔案的內容
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:singleLine="false"
android:maxLines="15"
android:text="@string/hello"
android:textSize="20dp"
android:textColor="#00FF00" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
**************************************************************
public class IO_FileContentActivity 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 = "test03.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);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());//text 太長的話,讓TextView 滾動
//列出Sdcard 裡的夾子和檔案,放上LISTVIEW
try {
File sdcardPATH = Environment.getExternalStorageDirectory();//找出SD的入徑
// String [] fileNamesArrayStr = sdcardPATH.list(); //用list(),將SD裡的資料夾和檔案以字串的方式收集在array
// File [] fileArray = sdcardPATH.listFiles(); //listFiles()則會加上完整入徑,列出入徑及資料夾+檔名的集合,存在File格是的陣列
File myDataPath = new File (sdcardPATH.getAbsolutePath() + "/fileio");
File [] fileArray = myDataPath.listFiles();
String tempStr = ""; //初始化
for (int i=0; i < fileArray.length; i++) {
if (fileArray[i].isFile()) { //只收集檔案,不要資料夾,但每筆資料會產生入徑(但無法用 fileNamesArrayStr來做,因為它是字串,無法判定是否為檔案還是資料夾
String str = ""; //用來接收每一筆的檔案名字串,但是會包含前面的入徑:/mnt/sdcard/fileio
str = fileArray[i].toString();
String strSub = "";// 用來去除多餘的入徑字串:/mnt/sdcard/fileio
strSub = str.substring(19, str.length()).toString(); //利用substring 去掉每筆最前面的19個字元:/mnt/sdcard/fileio
tempStr += strSub + "--" ; // 以 "--"為記號,分隔每筆處理好的資料,存成一筆字串
}
}
String result = ""; //設一變數來處理最後的"--"兩個字元,讓它不會在ListView上多產生一個空的cell
result = tempStr.substring(0, tempStr.length()-2);
final String[] strings = TextUtils.split(result, "--"); //以"--"為分節點將整筆字串切割成數個字串儲存成字串陣列,以顯示在螢幕上
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String filename = strings[position].toString();
Toast.makeText(Cq_IO_File01Activity.this, filename, Toast.LENGTH_SHORT).show();
readFile(filename);
}
});
} catch (Exception e) {
e.printStackTrace();
}
//readFile(); //讀出指定的檔到TEXTVIEW上
}// end of onCreate
public void readFile (String filename) {
String result = "";
try {
File mFilePath = new File (SD_PATH + FILE_PATH);
String mFileName = mFilePath + "/" + filename;
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)


