我有这段代码,只想创建一个新文件:
// 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...but我在openFileOutput命令上得到一个编译错误,上面写着‘未处理的异常类型FileNotFoundException’。
如果我在它周围放置一个try块来捕获该异常,错误将转移到写命令,说'gamFile‘不能被解决。
这是我在线程中尝试做的问题吗?或者是文件名字符串错了-应该是某个对象吗?
任何感激不尽的想法。
注: 1.我试过试块。2.此错误发生在编译时,在代码运行之前(我无法运行它,因为此编译错误阻止生成)。
发布于 2014-08-05 09:41:50
在函数openFileOutput的情况下,引发FileNotFoundException的原因有多个:
在文档中,它还声明文件名不能包含路径分隔符,因此请检查路径名是否符合此要求。
编辑:
try {
    FileOutputStream gamFile = openFileOutput(fileName, Context.MODE_PRIVATE);
    gamFile.write(totItemsStr.getBytes());
}
catch(Exception e) {
    // Log your error
}发布于 2014-08-05 09:28:36
请尝试在以下位置捕捉FileNotFoundException:
catch (FileNotFoundException e) {
    System.out.println("File not found");
}并检查控制台是否找到了“文件”。如果是这样,文件名是不正确的,您可能得到的唯一其他异常是I/O,但这不是问题所在。
发布于 2014-08-05 10:04:06
把你的代码包装在这样的试捕捉块中,
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”无法解决问题
https://stackoverflow.com/questions/25135252
复制相似问题