布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请输入查找的内容" /> <EditText android:id="@+id/edt" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:isScrollContainer="true" /> </LinearLayout>
package com.example.searchfile; import java.io.File; import android.os.Bundle; import android.app.Activity; import android.text.TextUtils; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText edt ; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edt = (EditText) findViewById(R.id.edt); tv = (TextView) findViewById(R.id.tv); findViewById(R.id.btn).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String key = edt.getText().toString().trim(); if(TextUtils.isEmpty(key)){ tv.setText("输入的不能为空"); }else{ tv.setText(searchFile(key)); } } }); } private String searchFile(String keyword){ String msg = ""; //获得根目录下的所有文件 File[] file = new File("/").listFiles(); //遍历此数组 for (int i = 0; i < file.length; i++) { if(file[i].getName().indexOf(keyword)>=0){ msg += file[i].getPath()+"\n"; } } if(msg.equals("")){ msg = "找不到此文件"; } return msg; } }
时间: 2024-10-08 01:19:35