2011-04-11 38 views
0

我正在构建一个读取文本文件的android应用程序。 现在,我在SD卡中有多个文本文件。 位置的文件是/ SD卡/文本文件/
文件名:的abc.txt def.txt ghi.txt在Android中的用户选择中动态读取文本文件

我想,当用户选择文件中的任何一个,所选择的文件应该被读取。 我知道代码读取单个文件 即

File sdcard = Environment.getExternalStorageDirectory(); 
File file = new File(sdcard,pathtofile); 
BufferedReader br = new BufferedReader(new FileReader(file)); 

pathtofile存储文件路径的abc.txt被定义。

有没有什么办法可以传递给文件对象为该用户选择 目前该文件的文件路径,它为的abc.txt,因为我已经在pathtofile

回答

0

您还可以制作文本文件夹中所有项目的列表,并将其保存在列表中供用户选择。

public class DirectoryBrowser extends ListActivity { 

private List<String> items = null; 
private File currentDirectory; 
private ArrayAdapter<String> fileList; 

@Override 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    currentDirectory = new File("/sdcard/textfile"); 
    getFiles(currentDirectory.listFiles()); 

} 

@Override 
protected void onListItemClick(ListView l, View v, int position, long id){ 
    int selectedRow = (int)id; 

     currentDirectory = new File(items.get(selectedRow)); 
     if(currentDirectory.isDirectory()){ 
      getFiles(currentDirectory.listFiles()); 
     }else{ 
      //if the selected file is not a directory. get the filename 
      currentDirectory.getPath(); 
     } 
} 

private void getFiles(File[] files){ 
    items = new ArrayList<String>(); 
    for(File file : files){ 
     items.add(file.getPath()); 
    } 
    fileList = new ArrayAdapter<String>(this,R.layout.list_text, items); 
    setListAdapter(fileList); 
} 


} 
+0

thanks ekouchiq – ProgramME 2011-04-12 07:15:30

0

您可以使用AlertDialog与定义其路径名单。

final CharSequence[] items = {"abc.txt", "def.txt", "ghi.txt"}; 

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setTitle("Pick a file"); 
builder.setItems(items, new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int item) { 
     //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); 

     File sdcard = Environment.getExternalStorageDirectory(); 
     File file = new File(sdcard,items[item]); 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
    } 
}); 
AlertDialog alert = builder.create();