从android中的sdcard读取数据

时间:2011-01-08 09:26:42

标签: android file

我只是想在模拟器上显示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();
  }
 }
}

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

最后我明白了。我修改过的代码如下所示..

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 个答案:

答案 0 :(得分:8)

下面的代码展示了如何从SDcard.simple中读取文件内容,在Sdcard中插入一个文本文件,并在程序中的代码下面实现。

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

答案 1 :(得分:4)

也许我在您的代码中错过了它,但我无法在其中发现任何Intent。对于要显示的文件,您必须使用Intent标记调用ACTION_VIEW

例如。

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的操作。然后通过将文件对象的路径连接到Uri来创建file://对象。您现在要做的就是通过指定uri和类型字符串来设置数据并输入意图。在我的例子中每个图像类型。但是,您可以只指定某种图像类型。一旦你的意图被设置并准备就绪,你可以通过以意图作为参数启动一个活动来启动它。

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