我正在尝试在内部存储中创建一个 txt 文件。 当我执行操作并调用负责创建文件的函数时,没有发生错误。但是,当我检查文件是否实际创建在/data/data/文件夹中时,我找不到包含我的包名称的文件夹。
哪里出错了?
Ps.: 我已经从这里看到了几个关于这个主题的链接,但在所有情况下都是一样的。
public void criarArq(Context mcoContext,String sFileName, String sBody){
File file = new File(mcoContext.getFilesDir(),"mydir");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
}
}
我这样调用这个函数...
criarArq(getApplicationContext(), arqNome, "teste");
谢谢大家的帮助!
---更新---
现在这是我的代码:
try {
FileWriter writer = new FileWriter(gpxfile);
writer.append("teste");
writer.flush();
writer.close();
Toast.makeText(InfoEntregasActivity.this, "created",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
//Don't eat the exception, do something with it, e.g.
Log.e("criarArq", e.toString()); //this will give you your error in the log cat
Toast.makeText(InfoEntregasActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
throw new RuntimeException(e); //this will bomb your program out for when the error is unrecoverable
}
我尝试使用和不使用 Toast(结果相同),但使用 Toast 时我总是收到“已创建”消息。
最佳答案
...no error occurs
你正在吃任何潜在的异常,所以我不太确定。
public void criarArq(Context mcoContext, String fileName, String body) {
File file = new File(mcoContext.getFilesDir(),"mydir");
file.mkdirs(); //no need to check exists with mkdirs
File gpxfile = new File(file, fileName);
try {
FileWriter writer = new FileWriter(gpxfile);
writer.append(body);
writer.flush();
writer.close();
} catch (IOException e) {
//Don't eat the exception, do something with it, e.g.
Log.e("criarArq", e.toString()); //this will give you your error in the log cat
throw new RuntimeException(e); //this will bomb your program out for when the error is unrecoverable
}
}
其他提示,mkdirs
制作多个级别并为您检查 exists
。
不要使用与类型相关的前缀,例如s...
它非常老式,早于现代 IDE。
查看文件的去向
Log.d("criarArq", gpxfile.toString());
关于java - 尝试保存并检查文件是否保存在内部存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035178/