【发布时间】:2017-04-16 15:54:54
【问题描述】:
我正在创建一个应用程序,它将在我手机的蓝牙文件夹中查找所有 .txt 文件,打开文件,获取特定内容(日期和运行时间)。
计算机通过蓝牙将 .txt 文件发送到手机,然后应用应检查该文件夹。
我可以使用什么样的功能来查找、打开和分析所有文件?
提前非常感谢。
【问题讨论】:
标签: android file bluetooth find
我正在创建一个应用程序,它将在我手机的蓝牙文件夹中查找所有 .txt 文件,打开文件,获取特定内容(日期和运行时间)。
计算机通过蓝牙将 .txt 文件发送到手机,然后应用应检查该文件夹。
我可以使用什么样的功能来查找、打开和分析所有文件?
提前非常感谢。
【问题讨论】:
标签: android file bluetooth find
首先,获取你要搜索的目录:
String path = Environment.getExternalStorageDirectory().toString()+"/bluetooth";
File directory = new File(path);
现在你可以得到这样的文件列表
File[] files = directory.listFiles();
现在我们遍历每个文件以查看其是否为 .txt 文件
StringBuilder text = new Stringbuilder;
for (File f : files)
{
if (f.isFile() && f.getpath().endswith(".txt")) {
//it is a txt file, now do your action
try {
//read file
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
br.readLine();
//read each line
while ((line = br.readLine())) {
//Write your conditions here
//add line to stringbuilder
text.append(line);
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
Log.d("Exception",e.toString());
}
}
}
如果在 Android M 或更高版本上运行,请添加此权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE
}, 10);
}
}
【讨论】: