在安卓系统中读取SD卡数据

3

我只想在模拟器上显示sdcard中的文件内容(如图像文件/视频文件/音乐文件等)。

以下是我的代码。

public class listfiles extends ListActivity {
 private ArrayList<String> item = null;
 private ArrayList<String> path = null;
 private String root="/";
 private TextView myPath;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sub);
        myPath = (TextView)findViewById(R.id.path);
        getDir(root);
    }

    private void getDir(String dirPath)
    {
     myPath.setText("Location: " + dirPath);

     item = new ArrayList<String>();
     path = new ArrayList<String>();

     File f = new File(dirPath);
     File[] files = f.listFiles();

     if(!dirPath.equals(root))
     {

      item.add(root);
      path.add(root);

      item.add("../");
      path.add(f.getParent());

     }

     for(int i=0; i < files.length; i++)
     {
       File file = files[i];
       path.add(file.getPath());
       if(file.isDirectory())
        item.add(file.getName() + "/");
       else
        item.add(file.getName());
     }

     ArrayAdapter<String> fileList =
      new ArrayAdapter<String>(this, R.layout.row, item);
     setListAdapter(fileList);
    }

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

  File file = new File(path.get(position));

  if (file.isDirectory())
  {
   if(file.canRead())
    getDir(path.get(position));
   else
   {
    new AlertDialog.Builder(this)
    .setIcon(R.drawable.icon)
    .setTitle("[" + file.getName() + "] folder can't be read!")
    .setPositiveButton("OK", 
      new DialogInterface.OnClickListener() {

       @Override
       public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
       }
      }).show();
   }
  }
  else
  {
   new AlertDialog.Builder(this)
    .setIcon(R.drawable.icon)
    .setTitle("[" + file.getName() + "]")
    .setPositiveButton("OK", 
      new DialogInterface.OnClickListener() {

       @Override
       public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
       }
      }).show();
  }
 }
}

在我的输出中,我得到了文件路径和文件名。但是当我点击该文件时,它不会显示内容。我该怎么做?谢谢。

最终我搞定了。我的修正代码如下所示...

public class SDCardActivity extends ListActivity {
 private List<String> item = null;
 private List<String> path = null;
 private String root="/sdcard";
 private TextView myPath;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // Intent intent=getIntent();

        setContentView(R.layout.sub);
        myPath = (TextView)findViewById(R.id.path);
        getDir(root);
    }

    private void getDir(String dirPath)
    {
     myPath.setText("Location: " + dirPath);

     item = new ArrayList<String>();
     path = new ArrayList<String>();

     File f = new File(dirPath);
     File[] files = f.listFiles();

     if(!dirPath.equals(root))
     {

      item.add(root);
      path.add(root);

      item.add("../");
      path.add(f.getParent());

     }

     for(int i=0; i < files.length; i++)
     {
       File file = files[i];
       path.add(file.getPath());
       if(file.isDirectory())
        item.add(file.getName() + "/");
       else
        item.add(file.getName());
     }

     ArrayAdapter<String> fileList =
      new ArrayAdapter<String>(this, R.layout.row, item);
     setListAdapter(fileList);
    }

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

  File file = new File(path.get(position));

  if (file.isDirectory())
  {
   if(file.canRead())
    getDir(path.get(position));
   else
   {
    new AlertDialog.Builder(this)
    .setIcon(R.drawable.icon)
    .setTitle("[" + file.getName() + "] folder can't be read!")
    .setPositiveButton("OK", 
      new DialogInterface.OnClickListener() {

       public void onClick(DialogInterface dialog, int which){
        // TODO Auto-generated method stub
           dialog.dismiss();
       }
      }).show();
   }
  }
  else
  {
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_VIEW);
      Uri uri = Uri.parse("file://" + file.getPath());
      String fname=file.getName();
      if(fname.endsWith(".jpeg")||fname.endsWith("png")||fname.endsWith(".gif"))
      {
          intent.setDataAndType(uri, "image/*");
          startActivity(intent);
      }
      else if(fname.endsWith(".mp4")||fname.endsWith(".3gp"))
      {
          intent.setDataAndType(uri, "video/*");
          startActivity(intent);
      }
      else if(fname.endsWith(".mp3"))
      {
          intent.setDataAndType(uri, "audio/*");
          startActivity(intent);
      }
      else  
          try {
              EditText tv = (EditText)findViewById(R.id.tn);
              StringBuilder text = new StringBuilder();

                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append('\n');

                    //Set the text
                    tv.setText(text);

                }
            }//try
            catch (IOException e) {
                //You'll need to add proper error handling here
            }//catch

  }
 }
}
2个回答

8
以下代码展示了如何从SD卡中读取文件内容。只需在SD卡中插入一个文本文件,并在您的程序中实现以下代码。
    try{
           File f = new File(Environment.getExternalStorageDirectory()+"/f1.txt");
           fileIS = new FileInputStream(f);
           BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
           String readString = new String(); 
           //just reading each line and pass it on the debugger
           while((readString = buf.readLine())!= null){
              textdata.setText(readString);
              Log.d("line: ", readString);
           }
        } catch (FileNotFoundException e) {
           e.printStackTrace();
        } catch (IOException e){
           e.printStackTrace();
        }

4
也许我在你的代码中错过了,但我没有发现任何Intent。您必须使用ACTION_VIEW标志调用Intent以显示您想要显示的任何文件。
例如。
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.parse("file://" + file.getPath());
intent.setDataAndType(imgUri, "image/*");
startActivity(intent);

你只需要创建一个 Intent 实例,并设置操作,这里我们使用的是 ACTION_VIEW。然后,通过将文件对象的路径与 file:// 连接起来,创建一个 Uri 对象。现在,您只需要通过指定 uri 和类型字符串,在意图中设置数据和类型。在我的示例中,每个图像类型都可以。但是,您也可以仅指定某种图像类型。一旦您的意图设置好并准备就绪,您可以使用意图作为参数启动 Activity 来触发它。

Android 将负责查找适当的应用程序来显示意图中的数据。


谢谢您的回复。但是我应该在哪里将您的代码插入到我的代码中呢? - sanjay
非常感谢,我终于明白了。 - sanjay
还有一个问题。在上面的代码中,我可以在模拟器上显示图像文件。使用相同的代码,如何分别显示文本文档、视频文件和音频文件?谢谢。 - sanjay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接