尝试创建文件时出现FileNotFound异常(Android)
我有以下代码,只是尝试创建一个新文件:尝试创建文件时出现FileNotFound异常(Android),android,file,Android,File,我有以下代码,只是尝试创建一个新文件: // Write to file in thread new Thread (new Runnable() { public void run() { // Write game data to a file String partStr = gameName.replace(" ", "_"); String fileName = partStr + "_g
// Write to file in thread
new Thread (new Runnable() {
public void run() {
// Write game data to a file
String partStr = gameName.replace(" ", "_");
String fileName = partStr + "_game.txt";
FileOutputStream gamFile = openFileOutput(fileName, Context.MODE_PRIVATE);
gamFile.write(totItemsStr.getBytes());
}
}).start(); // end of thread
…但是我在openFileOutput命令上得到一个编译错误,说“未处理的异常类型FileNotFoundException”
如果我在其周围放置一个try块来捕获该异常,则错误会移动到write命令,表示“gamFile”无法解决
问题是我试图在一个线程中这样做吗?或者是文件名字符串错误-应该是某个对象吗
任何想法都受到了感激
注:
1.我试过试块。
2.此错误发生在编译时,代码运行之前(我无法运行它,因为此编译错误阻止生成)。请尝试在以下位置捕获FileNotFoundException:
catch (FileNotFoundException e) {
System.out.println("File not found");
}
并检查控制台是否未找到文件。
如果文件名不正确,则您可能得到的唯一其他异常是I/O,但这不是问题所在。对于函数
openFileOutput
,由于多种原因引发FileNotFoundException
:
- 如果创建文件的目录不存在
- 如果由于权限问题而无法创建文件
try {
FileOutputStream gamFile = openFileOutput(fileName, Context.MODE_PRIVATE);
gamFile.write(totItemsStr.getBytes());
}
catch(Exception e) {
// Log your error
}
将代码包装在try-catch块中,如下所示
new Thread (new Runnable() {
public void run() {
try{
// Write game data to a file
String partStr = gameName.replace(" ", "_");
String fileName = partStr + "_game.txt";
FileOutputStream gamFile = openFileOutput(fileName, Context.MODE_PRIVATE);
gamFile.write(totItemsStr.getBytes());
}catch (Exception e){
// exception found -> do something
e.printStacktrace();
}
}
}).start(); // end of thread
它应该修复您未处理的FileNotFoundException和无法解决的“gamFile”问题创建文件对象,如File fileobj=new File(fileName);并将fileObj指定给FileOutputStream。这不起作用-openFileOutput的第一个参数必须是字符串类型。清单文件中的写入权限是否已完成?根据指南,我只需要用于外部存储-我想使用internal.tested代码。很好,把所有东西都放在试抓块中,这应该是评论而不是回答对不起!但这里不是这样的。你应该给出答案。这应该是你的评论。你第一次是对的-我用了一个try块,但没有把所有的行都放在块中。投票支持你的答案(但给出了第一个答案的完整答案)。问题是,错误发生在编译时-我甚至还没有尝试运行代码!所以文件名还没有定义。根据文档,调用应该使用内部存储空间,因此路径是在内部定义的,不是吗?因为您必须在
try
块中使用gamFile。它将在此作用域中定义。是否包含“gamfile.write(toItemStr.getBytes());”对不起,我的错-我没有这样做-前面的问题给出了答案。