Saturday, December 15, 2012

How to read all .txt (Text File) from SD Card in Android



public class FindFilesFromSDCardRanjit extends Activity {
TextView tvFileList;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_files_from_sdcard);
tvFileList = (TextView) findViewById(R.id.textViewFiles);
FindFileNames_Path("\\sdcard");
}

public void FindFileNames_Path(String dir) {

File directory = new File(dir);

if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}

// create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {

public boolean accept(File dir, String name) {
// if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};

String[] filenames = directory.list(filefilter);

for (String name : filenames) {
System.out.println(name);
tvFileList.setText(tvFileList.getText() + "\n" + name);
}
}
}


--------------------
Main xml file
--------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textViewFiles"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="List of files"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

No comments:

Post a Comment