getAssets()。列表在我的Android应用程序中太慢了。我有近3000个文件,在某些设备上只需要MINUTES来获取所有文件名。 所以,相反,我想创建一个带有文件树的python脚本的json文件,并且必须很容易从特定的子目录中找到所有文件和目录(名称)。
所以没有json的默认实现是这样的:
progressView.startProgressing(duration: 5.0, resetProgress: true) {
// Set the next things you need... change to a next item etc.
}
现在我必须使用加载的json filetree来查找特定路径的内容
这是一个python脚本:
public String[] listAssets(String path) throws IOException {
return getAssets().list(path);
}
脚本来自stackoverflow。现在,我有一个问题如何解析它:
import os
import json
path = "/Users/xxx/somepath"
def path_to_dict(path):
d = {'name': os.path.basename(path)}
if os.path.isdir(path):
d['type'] = "directory"
d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\
(path)]
else:
d['type'] = "file"
return d
with open("tree.json", "w") as tf:
tf.write(json.dumps(path_to_dict(path)))
我通过" /"分裂路径并且必须以某种方式通过所有子目录并递归找到正确的子目录,但我不知道如何实现这个" findSubdirectory"方法
答案 0 :(得分:0)
好的,想出不同的(最有效的方式):
声明:
HashMap<String, String> files;
JSONObject fileTree;
onCreate()中的:
try {
fileTree = new JSONObject(readTextFromAssets("tree.json", "\n"));
}
catch (Exception e){
e.printStackTrace();
}
files = toMap(fileTree);
主要功能:
public String[] listAssets(String path) throws IOException {
String f = files.get(path);
if(f != null){
return f.split(Pattern.quote("|"));
}
String[] l = getAssets().list(path);
files.put(path, join(l, "|"));
return l;
}
辅助函数:
public static String join(String[] values, String delimiter) {
StringBuilder strbuf = new StringBuilder();
boolean first = true;
for (String value : values)
{
if (!first) { strbuf.append(delimiter); } else { first = false; }
strbuf.append(value);
}
return strbuf.toString();
}
public static HashMap<String, String> toMap(JSONObject object) {
HashMap<String, String> map = new HashMap<>();
try {
Iterator<String> keysItr = object.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
String value = object.getString(key);
map.put(key, value);
}
}
catch (Exception e){
e.printStackTrace();
}
return map;
}
保存缓存:
fileTree = new JSONObject(files);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "files.jpg");
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(fileTree.toString());
output.close();
}
catch (Exception e){
e.printStackTrace();
}