-1
public class SDCardFileManager {
public long i = 0;
public void onDirList(){
try {
File rootFile = new File("/");
Log.d("test", "traverse start");
String json = GsonUtil.list2Json(new SDCardFile(rootFile).list);
Log.d("test", "traverse finished");
File file = new File("/sdcard/file.json");
if (file.exists()) {
file.delete();
}
file.createNewFile();
Log.d("test", "ready to store ");
OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
oStreamWriter.append(json);
oStreamWriter.close();
Log.d("test", "json file was stored at "+file.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class SDCardFile{
private String filename;
private boolean isDirectory;
private String size = "";
private String date = "";
public List<SDCardFile> list = new ArrayList<SDCardFileManager.SDCardFile>();
public SDCardFile(File file) {
i++;
this.filename = file.getName();
this.isDirectory = file.isDirectory();
if (!isDirectory) {
size = formatSize(file.length());
date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(file.lastModified());
}else{
File[] DirFiles = file.listFiles();
if (DirFiles != null) {
for (final File dirFile : DirFiles) {
list.add(new SDCardFile(dirFile));
}
}
}
}
private String formatSize(long length){
String size = "";
if (length<1024) {
size = String.valueOf(length)+"B";
}else if (length>=1024&&length<1024*1024) {
size = String.valueOf(length/1024)+"KB";
}else if (length>=1024*1024&&length<1024*1024*1024) {
size = String.valueOf(length/(1024*1024))+"MB";
}else if (length>=1024*1024*1024) {
size = String.valueOf(length/(1024*1024*1024))+"GB";
}
return size;
}
}
我需要遍歷整個文件系統和存儲作爲json.I使用上面的代碼,解決了要求,但同時它遍歷一個大目錄,它給我一個出來的內存crash.Can任何人都可以告訴我如何解決這個問題?或者還有其他方法可以滿足要求嗎?內存不足而導線Android的文件系統
也許對這個問題存在一些誤解。 我不需要獲取文件的內容。我只需要它的名稱,創建時間,大小和目錄結構。然後將其存儲到json文件中,以便其他客戶端可以將其分析爲文件系統樹。
顯示堆棧跟蹤。那個目錄有多大? –