Android:如何显示已下载的文本文件?

时间:2016-05-27 09:31:54

标签: android listview

我使用了Download Manager Class从服务器下载文本文件并将其存储在公共外部存储中。然后我要显示文本文件,可能是使用listView类。我在网上搜索过,发现有很多例子展示了如何从App的资源中显示文本文件。但是,如何显示存储在特定文件路径中的文件?

非常感谢。

3 个答案:

答案 0 :(得分:0)

在您的布局中,您需要显示文字的内容。 TextView是显而易见的选择。所以你会有这样的事情:

<TextView 
android:id="@+id/text_view" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"/>

您的代码将如下所示:

//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');
}
br.close();
}
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);

此外,将外部存储读取权限放入清单文件:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

OR 您也可以使用默认意图来完成JOB!

File txtfile = new File("/sdcard/some_file.txt");
Intent i = new Intent();
i.setDataAndType(Uri.fromFile(txtfile), "text/plain");
startActivity(i);

-

答案 1 :(得分:0)

尝试以下代码。

  private void openFile() {

     File file = new File("file_path");
     Uri path = Uri.fromFile(file);
     Intent intent = new Intent(Intent.ACTION_VIEW);
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     intent.setAction(Intent.ACTION_VIEW);
     intent.setData(path);
     intent.setType("text/plain");
     try {
         startActivity(intent);
     } catch (ActivityNotFoundException e) {
         Toast.makeText(getActivity(), "No application found",
                Toast.LENGTH_SHORT).show();
     }
 }

答案 2 :(得分:0)

您可以使用与文件扩展名兼容的外部应用程序中的以下代码打开SD卡中的文件,

   public void openDocument(String fileName) {

    File file = new File(Environment.getExternalStorageDirectory(), DATA_DIRECTORY + "/" + fileName);
    Uri fileUri = Uri.fromFile(file);
    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
    String extension = MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
    String mimetype =  MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    if (extension.equalsIgnoreCase("") || mimetype == null) {
        // if there is no extension or there is no definite mimetype, still try to open the file
        intent.setDataAndType(fileUri, "application/*");
    } else {
        intent.setDataAndType(fileUri, mimetype);
    }
    // custom message for the intent
    startActivity(Intent.createChooser(intent, "Choose an Application:"));


}