2013-07-17 69 views
0

我創建了寫日誌文件中的類和作品非常好:在android中保存自定義日誌文件的位置?

public class LogFile { 

String route; 
Context context; 

public LogFile(Context context, String date) { 
    this.context = context; 
    this.route= context.getFilesDir() + "/log_"+date+".txt"; 
} 

public void appendLog(String text){  

    File logFile = new File(ruta); 

    if (!logFile.exists()){ 
     try{ 
      logFile.createNewFile(); 
     } 
     catch (IOException e){ 
      e.printStackTrace(); 
     } 
    } 
    try{ 
     BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
     buf.append(text); 
     buf.newLine(); 
     buf.close(); 
    } 
    catch (IOException e){ 
     e.printStackTrace(); 
    } 
} 

}

但是,這產生的路線是/data/data/com.myAplication.myAplication/files/log_20130717。 txt 而我無法從我的設備訪問此目錄。如果設備出現問題,我需要訪問此文件。通過我的平板電腦的文件瀏覽器,我可以看到目錄:/ root/data和/ root/Android/data。 Android是否有助於在這些目錄中創建我的應用程序目錄?否則,我試圖把文件放在「sdcard/log_20130717.txt」中,但是我獲得了權限被拒絕的權限。

你建議我做什麼?

+1

如果隱私不是問題,爲什麼不把它保存在SD卡上?而且,究竟是「sdcard/log.file」。這是一條路嗎?您是否嘗試過獲取外部存儲路徑(通過'String exPath = Environment.getExternalStorageDirectory()。getAbsolutepath()'),然後將文件保存到exPath +「/」+ log.file? – Vikram

+0

感謝這個作品。但是如果我的設備沒有SD卡呢? – kiduxa

+1

對於我正在處理的應用程序,我將許多文件保存到內存中。當這些文件需要更新時,我從內部存儲器中檢索它們,更新它們,並將它們寫回。如果這是你正在尋找的,我可以用代碼示例發佈答案。 – Vikram

回答

1

您可以使用droidQuery API輕鬆地寫入文件。例如,這會做你想要什麼:

$.write(text, FileLocation.EXTERNAL, "log_"+date+".txt", true, true); 
0

到目前爲止,這是我的作品。多一點點研究,我發現瞭如何我的數據存儲在路徑/根/安卓/數據/:

public class LogFile { 

String name; 
Context context; 


public LogFile(Context context, String name) { 

    this.context = context; 
    this.name="log_"+name+".txt"; 

} 

public void appendLog(String text){  

    File logFile = new File(context.getExternalFilesDir(null), name); 


    if (!logFile.exists()){ 
     try{ 
      logFile.createNewFile(); 
     } 
     catch (IOException e){ 
      e.printStackTrace(); 
     } 
    } 
    try{ 
     BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
     buf.append(text); 
     buf.newLine(); 
     buf.close(); 
    } 
    catch (IOException e){ 
     e.printStackTrace(); 
    } 
} 

}

使用

File logFile = new File(context.getExternalFilesDir(null), name); 

的Android會自動創建一個目錄和我的項目名稱,得到:/root/Android/data/com.myAPP.myApp/files/。在文件內部,我獲得了我創建的自定義日誌,甚至是重要的,當我的應用程序被卸載時,該目錄被刪除。另外,用戶也可以訪問這個文件。