试图保存并检查文件是否保存在内部存储
问题描述:
我试图在内部存储创建一个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
}
我尝试与不吐司(相同的结果),但与吐司我总是得到“创造”味精。
答
...没有发生错误
你吃任何潜在的异常,所以我就不会这么肯定。
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...
这是相当老派,约会现代IDEs。
要查看你的文件要
Log.d("criarArq", gpxfile.toString());
你不应该忍气吞声例外。 'catch(Exception e){}'在适当的时候记录错误,恢复或崩溃。 –
当您创建文件时,您看不到错误,因为您的“try ... catch”会忽略它。您应该更改'criarArq()'方法来声明可以抛出的异常,然后UI代码将有一个'try ... catch',它决定发生错误时应该怎么做。 –
@ChristopherSchneider和Code-Apprentice,我已经解决了这个问题,但仍然处于相同的情况。感谢帮助。 “ – rponciano