废话不多说,直接上代码:
public class ReadLocalFileActivity extends AppCompatActivity {
private ListView listView;
private List<File> files = new ArrayList<>();
private ArrayAdapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_loacal_file);
listView = findViewById(R.id.lv_file);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String absolutePath = files.get(position).getAbsolutePath();
Log.i("lala","=position=>" + position + " absolutePath==>" + absolutePath);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
File file = files.get(position);
Uri contentUri = FileProvider
.getUriForFile(ReadLocalFileActivity.this,
getPackageName()+".read_txt_provider", file);
intent.setDataAndType(contentUri, "text/plain");
startActivity(intent);
}
});
getLocalFileData();
}
@SuppressLint("CheckResult")
private void getLocalFileData() {
String basePath = Environment.getExternalStorageDirectory().getPath();
File rootFile = new File(basePath);
boolean exists = rootFile.exists();
if (!exists){
adapter.notifyDataSetChanged();
return;
}
Observable.just(rootFile)
.flatMap(new Function<File, Observable<File>>() {
@Override
public Observable<File> apply(@NonNull File file) throws Exception {
return listFiles(file);
}
})
.filter(new Predicate<File>() {
@Override
public boolean test(@NonNull File file) throws Exception {
return file.getName().endsWith(".txt");
}
})
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<File>>() {
@Override
public void accept(List<File> s) throws Exception {
files.addAll(s);
adapter.notifyDataSetChanged();
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.e("lala","=throwable==>" + throwable.getMessage());
}
});
}
private Observable<File> listFiles(File file) {
if (file.isDirectory()) {
return Observable.fromArray(file.listFiles())
.flatMap(new Function<File, Observable<File>>() {
@Override
public Observable<File> apply(@NonNull File file) throws Exception {
return listFiles(file);
}
});
} else {
return Observable.just(file);
}
}
}
layout布局就是一个简单的listview
<-----------end----------->
|