[英]Android-How to create a new writeable file?
I have a jobIntentService that create a file to add some text in it but I get the error /data/user/0/com.example.projet/files/log.txt (Is a directory)
.我有一个 jobIntentService 创建一个文件以在其中添加一些文本,但我收到错误
/data/user/0/com.example.projet/files/log.txt (Is a directory)
。 I don't know what I did wrong... Here is my code:我不知道我做错了什么......这是我的代码:
public void ecritureLog(Context context) {
File path = context.getFilesDir();
File file = new File(path, "log.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
Log.d("Debug ecriture log", "exeption levée : " + e.getMessage());
}
}
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write("text-to-write".getBytes());
stream.close();
} catch (Exception e) {
Log.d("Debug ecriture log", "exeption levée : " + e.getMessage());
}
}
Furthermore, what I want is a sort of log file so I want to access it from the phone but /data/user/0/com.example.projet/files/log.txt
is an hidden path to the user... I already tried Environment.getDataDirectory()
but I don't have the permission even if they are in the manifest...此外,我想要的是一种日志文件,所以我想从手机访问它,但
/data/user/0/com.example.projet/files/log.txt
是用户的隐藏路径......我已经尝试过Environment.getDataDirectory()
但即使它们在清单中,我也没有权限...
Edit: Here is my manifest permissions:编辑:这是我的清单权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Thanks for your help !谢谢你的帮助 !
With all the comment of you guys this work so there is the final code:有了你们的所有评论,这项工作有了最终的代码:
public void ecritureLog(Context context) {
File path = context.getExternalFilesDir(null);
File file = new File(path, "/log.txt");
if (file.exists() && file.isDirectory() ) {
if (!file.delete()){
Log.d("Debug ecriture log", "!file.delete()");
return;
}
}
try {
FileOutputStream stream = new FileOutputStream(file);
Log.d("Debug ecriture log", "chemin: " +file.getAbsolutePath());
stream.write("text-to-write".getBytes());
stream.close();
} catch (Exception e) {
Log.d("Debug ecriture log", "exeption levée : " + e.getMessage());
}
}
Thanks !谢谢 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.