java - Android-如何创建一个新的可写文件?
问题描述
我有一个 jobIntentService ,它创建一个文件以在其中添加一些文本,但出现错误/data/user/0/com.example.projet/files/log.txt (Is a directory)
。我不知道我做错了什么......这是我的代码:
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());
}
}
此外,我想要的是一种日志文件,所以我想从手机访问它,但它/data/user/0/com.example.projet/files/log.txt
是用户的隐藏路径......我已经尝试过Environment.getDataDirectory()
,但即使它们在清单中,我也没有权限。 ..
编辑:这是我的清单权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
谢谢你的帮助 !
解决方案
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 !
推荐阅读
- android - 来自 Firebase 的 RecyclerView 图像无法加载三个活动中的一个
- kubernetes - 新部署将进入 ImagePullBackOff
- java - IntelliJ 卡住运行 Cucumber 测试(未注册 BaseStepListener)
- reactjs - 启动屏幕后导航容器消失
- java - c3p0 连接池无法更改数据库
- windows-10 - 在 Sublime 中更改折叠文本的颜色
- android - 如何在 ConstraintLayout 中的图像之间的两行中对齐 TextView
- github - 如何通过 github 操作将 helm chart 部署到 ecr?
- storybook - 故事书 - 如何在不打开 iframe 的情况下获得部分链接
- amazon-web-services - 将 Lambda context.awsRequestId 与 API 响应的响应标头中的对象映射