本文实例为大家分享了android遍历所有文件夹和子目录来搜索文件,供大家参考,具体内容如下
java代码:
import java.io.File; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class ShuosouwenjianActivity extends Activity implements OnClickListener { private File file; private String path; private String info; private String key; //关键字 private TextView result; // 显示结果 private EditText et; // 编辑view private Button search_btn; // button view @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); result = (TextView)findViewById(R.id.TextView_Result); et = (EditText)findViewById(R.id.key); search_btn = (Button)findViewById(R.id.button_search); // file = new File(Environment.getExternalStorageDirectory().getPath()); file = new File("/sdcard/"); info = getString(R.string.info); search_btn.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub path = ""; result.setText(""); key = et.getText().toString(); BrowserFile(file); } public void BrowserFile(File fileold) { if (key.equals("")) { Toast.makeText(this, getString(R.string.pleaseInput), Toast.LENGTH_LONG).show(); } else { search(fileold); if (result.getText().equals("")) { Toast.makeText(this, getString(R.string.notFound), Toast.LENGTH_SHORT).show(); } } } private void search(File fileold) { try{ File[] files=fileold.listFiles(); if(files.length>0) { for(int j=0;j-1) { path += "\n" + files[j].getPath(); result.setText(info+path); //shuju.putString(files[j].getName().toString(),files[j].getPath().toString()); } } else{ this.search(files[j]); } } } } catch(Exception e) { } } }
MAIN.XML代码:
<&#63;xml version="1.0" encoding="utf-8"&#63;>
strings.xml代码:
<&#63;xml version="1.0" encoding="utf-8"&#63;>Hello World, Activity07! 文件搜索 搜索 系统SDCard目录文件路径:\n 请输入关键字! SD卡中没有相关文件!! 读取路径出错!!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。