【问题标题】:How to Choose a file from files in SDCard?如何从 SDCard 中的文件中选择文件?
【发布时间】:2014-04-23 17:43:07
【问题描述】:

我的安卓 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卡并选择 他想要的文件?

【问题讨论】:

标签: android sd-card


【解决方案1】:

您需要在此处创建文件选择器/浏览器。有很多可用的库,您可以使用它们来实现所需的功能。这是一个 -

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();
   }                   
}

【讨论】:

  • 感谢您的帮助。我有两个问题:1.我知道“FILE_CHOOSER”是一个常数,但常数的值是多少? 2. 我使用 filechooser 作为库,我应该在我的 android 中将 FileChooser 声明为 Activity 吗?
  • 您可以为其分配任何值:)。是的,你可以这样做,但如果你不需要更改代码中的任何内容,lib 会很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多