我正在尝试在内部存储中创建一个txt文件。当我执行操作并调用负责创建文件的函数时,不会发生任何错误。但是,当我检查文件是否实际在/ data / data /文件夹中创建时,找不到包含包名称的文件夹。
错误在哪里?
附言:我已经从这里看到了有关该主题的几个链接,但是在所有情况下都是相同的情况。
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时,我总是会得到“已创建”的味精。
...没有错误发生
您正在吃任何潜在的例外,所以我不确定。
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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句