我的android SD卡上有一些文本文件,我需要访问其中一个。 我遇到了以下代码here:
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
但是在这部分代码中:
//Get the text file
File file = new File(sdcard,"file.txt");
指定了文本文件的名称,但我需要用户选择他想要的文本文件(来自SD卡中的文本文件)。那么我怎样才能让用户看到SD卡并选择 他想要的文件?
答案 0 :(得分:4)
您需要在此处创建文件选择器/浏览器。有许多库可用于您可以实现所需的功能。这是一个 -
https://code.google.com/p/android-file-chooser/
此外,首页需要必要的代码。想要调用文件选择器,您需要编写这些代码行 -
Intent intent = new Intent(this, FileChooser.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".txt"); //can be used for multiple filters
intent.putStringArrayListExtra("filterFileExtension", extensions);
startActivityForResult(intent, FILE_CHOOSER);
并且,用于回调以获取用户的路径Selected File
-
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == FILE_CHOOSER) && (resultCode == -1)) {
String fileSelected = data.getStringExtra("fileSelected");
Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();
}
}