遍歷系統文件目錄,能夠查找到咱們須要的文件,方便記錄文件的目錄地址(不想找database在系統中的位置,就寫了這麼個玩意兒,必定要開啓一個線程,否則手機文件多,可能會崩潰)數據庫
優勢是:不管手機中有什麼文件,都可以便利出來。缺點是手機文件越大,遍歷須要的時間久越長久。json
示例代碼以下:網絡
1 private void printFileList(int level,String fileName){ 2 level++; 3 File file = new File(fileName); 4 if(file.isDirectory()){//判斷是不是文件夾 5 if(file.listFiles()!=null){ 6 for (File temp:file.listFiles()){ 7 printFileList(level,temp.getAbsolutePath()); 8 } 9 } 10 11 }else{//是文件直接打印當前目錄 12 StringBuilder sb = new StringBuilder(); 13 for (int i = 1;i<level;i++){ 14 sb.append("-"); 15 } 16 System.out.println(sb.toString()+fileName); 17 } 18 19 }
調用代碼以下:app
printFileList(0,"/");
在開發應用的時候,爲了省事兒,客戶端的筒子們可能會獲得一個完整的db文件,而不是json串。好比手機號查詢系統,點餐系統,醫療系統,都會將服務端生成的db文件直接打包,客戶端調用接口的時候返回這個db文件進行操做,這樣能夠保證本地機器未聯網的狀況下也能夠進行正常的操做。ui
示例代碼以下:spa
(文件只加載了一次,若是db文件須要更新,請縮小if的範圍)線程
1 /** 2 * 獲取數據庫路徑,將assets目錄中的文件加載到dababase目錄下面。一樣咱們能夠直接讀取網絡下載是數據,而後直接將數據流存放到本地demo.db文件中 3 * @param context 4 * @return 5 */ 6 private String getDataBasePath(Context context) { 7 String dbName = "demo.db"; 8 String dbDir = mContext.getDatabasePath(dbName).getAbsolutePath().replaceAll(dbName,"");//沒有文件名 9 String dbPath = mContext.getDatabasePath(dbName).getAbsolutePath();//有文件名 10 File pathFile = new File(dbPath); 11 File dirFile = new File(dbDir); 12 if (!pathFile.exists()) {//檢查一下 database 目錄是否存在 13 try { 14 if (!dirFile.exists()) {//database目錄不存在,新建 15 dirFile.mkdir(); 16 } 17 if(!pathFile.exists()){//文件不存在就直接建立新的文件 18 pathFile.createNewFile(); 19 } 20 // 獲得 assets 目錄下咱們實現準備好的 SQLite 數據庫做爲輸入流 21 InputStream is = context.getAssets().open(dbName); 22 // 輸出流 23 OutputStream os = new FileOutputStream(dbPath); 24 // 文件寫入 25 byte[] buffer = new byte[1024]; 26 int length; 27 while ((length = is.read(buffer)) > 0) { 28 os.write(buffer, 0, length);//寫入到/data/data/packagename/databases/demo.db目錄下 29 } 30 // 關閉文件流 31 os.flush(); 32 os.close(); 33 is.close(); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 } 38 39 return dbPath; 40 }