Rabu, 30 Januari 2013

List files with specified extension using listFiles() with FilenameFilter.

To list all files in a folder, we can call listFiles() method. If you want to list only the files with specified extension, you can call listFiles(FilenameFilter filter) with custom FilenameFilter.

Example:

package com.example.androidlistfile;

import java.io.File;
import java.io.FilenameFilter;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

File root;
File[] fileArray;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
setContentView(textView);

root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fileArray = root.listFiles(new FilenameFilter(){

@Override
public boolean accept(File dir, String filename) {
return filename.toLowerCase().endsWith(".jpg");
}});

String f = root.getAbsolutePath() + "\n\n";
for(int i=0; i < fileArray.length; i++){
f += fileArray[i].getName() + "\n";
}
textView.setText(f);
}

}

List files with specified extension using listFiles() with FilenameFilter.

0 komentar:

Posting Komentar

Copyright © 2012 Codding News All Right Reserved