Java 在Android中,如何获取任何文本文件的文件路径并从SD卡读取?

Java 在Android中,如何获取任何文本文件的文件路径并从SD卡读取?,java,android,sd-card,Java,Android,Sd Card,我有这么多的链接相关的图像文件,但没有得到任何文字相关。有具体的文本文件打开解决方案,但我需要一般的解决方案,而不是硬编码的SD卡上的文件位置。我正在构建一个Android应用程序,它可以复制TextView中文件的链接,并从SD卡的另一个TextView中读取该文件的内容。一个用于打开SD卡的按钮: public void onClick(View v) { Intent intent = new Intent(); intent.setType

我有这么多的链接相关的图像文件,但没有得到任何文字相关。有具体的文本文件打开解决方案,但我需要一般的解决方案,而不是硬编码的SD卡上的文件位置。我正在构建一个Android应用程序,它可以复制TextView中文件的链接,并从SD卡的另一个TextView中读取该文件的内容。一个用于打开SD卡的按钮:

public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("text/plain"); //open only for text file 
            intent.setAction(Intent.ACTION_GET_CONTENT);

            //broadcast the supported media to choose for file to open 
            startActivityForResult(Intent.createChooser(intent, "Select file"), MY_INTENT_CLICK);
        }
这是onActivityResult的代码

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == MY_INTENT_CLICK) {
            if (data == null) return;

            //String sel_file_path;
            String sel_file_path;
            Uri sel_file_uri = data.getData();

            sel_file_path = FileText.getPath (getApplicationContext(), sel_file_uri);
            setTextViews (sel_file_path);       
        }
    }
}
从FileText获取文件路径后,它使用此方法查看文本文件的链接和内容

//show the link and display the content of the file 
private void setTextViews(String sel_file_path) {

    //copy the file link to textview
    this.txtpath.setText("File path: " +sel_file_path);

    //display the text file
    try {

        File file1 = new File(sel_file_path);
        //System.out.println("Path : " + file1);
        FileInputStream fis = new FileInputStream(file1);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));

        String datatoread = "";
        String inBuffer = "";

        //Read the line of the file, store it in temporary variable and append it to inBuffer
        while ((datatoread = br.readLine()) != null) {
            inBuffer += datatoread + "\n";                   
        }

        txtdsp.setText(inBuffer);
        br.close();
        //Toast.makeText(getBaseContext(), "Load file reading", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }

    Log.d("MainActivity", "File Path: "+sel_file_path); 
}   
我在设备上运行时出错:

没有这样的文件或目录


您正在记录选择文件路径。它看起来像什么?另外,什么是FileText.getPath?你们是如何处理不返回文件,而是返回指向ContentProviders的Uri值的操作内容结果的?@Commonware[FileText]是另一个类,从那个里我们可以得到所选文件的路径,并将该文件路径位置返回到[sel_file_path]字符串,若你们需要代码,那个么我会给你们发邮件。从[ACTION\u GET\u CONTENT]弹出一个窗口,您可以选择已经安装在手机中的文件读取器,如quick-office。如果您需要代码,我将向您发送邮件-我对代码不感兴趣。但是,它可能有bug,或者您对它的使用可能有bug。只需说ACTION\u GET\u CONTENT返回一个Uri,是的,它确实返回了Uri。我从中获取文件路径,并将Uri粘贴到textview中,然后从该文本链接读取文件内容。如果你在这方面有任何其他想法,你能给我提供一些链接来解决这个问题吗,如果可能的话,他们会给我发一些代码片段谢谢。。