gpt4 book ai didi

java - 扫描目录并显示在 TextView 中

转载 作者:行者123 更新时间:2023-12-01 15:16:24 24 4
gpt4 key购买 nike

我正在递归扫描目录,但我想在 TextView 中显示扫描的文件。我正在使用线程,但无法在 textView 中显示文件名。你能给我一个如何做到这一点的例子吗?

new Thread(new Runnable() { 
public void run(){
fw.walk(new File("/"));
}

}).start();

for (File f : list) {
if (f.isDirectory()) {
walk(f);
} else {
Log.d("sdf", "File: " + f.getAbsoluteFile());


}
}

最佳答案

使用此代码..它从根目录开始,递归迭代所有目录和子目录,以在 TextView 中打印文件名。

根据您的需要格式化文本输出。这是逻辑...

<小时/>

更新:好的,我忍不住自己尝试一下,这是工作代码。

这是 AsyncTask 内部类,在您拥有 textView 的 Activity 中定义它,您必须在其中显示文件名。 AsyncTask 类使用上面给定的函数,因此在同一个 Activity 中保持原样。

private class fileNames extends AsyncTask<String, Integer, String> {
TextView tv,tv_temp;
File f;
ProgressDialog pg;


public fileNames(File f,TextView tv, Context c) {
this.f=f;
this.tv=tv;
tv_temp=new TextView(c);
pg =new ProgressDialog(c);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();

pg.setTitle("loading");
pg.show();
}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("Start : fileNames : doInBackground");
printFileNames(f,tv_temp);

return tv_temp.getText().toString();

}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv.setText(result);
pg.dismiss();

}

}

函数定义:

public void printFileNames(File fName,TextView tv){
int count=0;
if(fName.listFiles()!=null)
for (File f : fName.listFiles()) {
if (f.isDirectory()){

String name = f.getName();
System.out.println("Dir:"+ name + "\n" );
tv.setText(tv.getText().toString()+"\n" + "Dir:"+ name + "\n" );
printFileNames(f, tv);
}else{
String name = f.getName();
System.out.println(" File:"+ name +"\n" );
tv.setText(tv.getText().toString()+ " File:"+ name +"\n" );
count++;

}

}
}

将此代码放在 Activity 中的任何位置,[在您的 onCreate() 中,比如说]:

TextView fileNameTextView = (TextView)findViewById(R.id.thisfile);
File sdCardRoot = Environment.getExternalStorageDirectory();
new fileNames(sdCardRoot,fileNameTextView ,YourCurrentActivity.this).execute();

关于java - 扫描目录并显示在 TextView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11537820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com