Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

file - read data from sdcard in android

I just wanna display the contents of files from sdcard on emulator (as image files/video files/music files like that).

Below is my code.

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

In my output I got file path & file name. But when i click the file, it won't show the contents. What should I do for that? Thanks

Finally i got it.My corrected code is shown below..

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

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

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

  }
 }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Below code show you how to read the file content from the SDcard.simple insert one text file in Sdcard and implement below code in your program.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...