我创建了一个用于编写日志文件的类,并且运行良好:
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有助于在任何这些目录中创建我的aplication目录吗?否则,我试图将文件放在“sdcard / log_20130717.txt”中,但我得到了许可被拒绝。
你建议我做什么?。
答案 0 :(得分:2)
将其放在externalFilesDir()
中,不要忘记获取android.permission.WRITE_EXTERNAL_STORAGE
。
答案 1 :(得分:1)
您可以使用droidQuery API轻松写入文件。例如,这将做你想要的:
$.write(text, FileLocation.EXTERNAL, "log_"+date+".txt", true, true);
答案 2 :(得分:0)
到目前为止,这对我有用。经过一番研究后,我发现了如何将数据存储在路径/ root / Android / data /中:
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会自动创建一个名为my project的目录,获取:/root/Android/data/com.myAPP.myApp/files/。内部文件我创建了自定义日志,甚至很重要,当我的应用程序被卸载时,此目录会被删除。此外,用户也可以访问此文件。