0

我的问题出在以下代码中。

问题是当我调用alreadyUser(String username)如果文件在系统上不存在时,它会给出 FileNotFoundException。我想克服这个错误,但我想不通。

因此,在应用程序启动时,系统会要求输入 unname 并通过。然后调用 alreadyUser 方法,如果文件尚未创建,它会给出错误(例如,我手动创建它)。下次我启动程序时,如果文件已经存在,则不能用新文件切换,因为旧数据将消失 :)

public final class TinyBase {

    final static String FILENAME = "KEYVALUES.txt";
    static FileOutputStream fos = null;
    static FileInputStream fis = null;

    protected static void createUser(String username, String password)

    protected static boolean loadUser(String username, String password)

    protected static boolean alreadyUser(String username) {
        String encode = new String(username);
        String compare = null;
        boolean flag = false; // true - ok no such user ; false - fail username
                                // already in use
        try {
            /* ERROR IS HERE */
            fis = new FileInputStream(FILENAME);
            /* ERROR IS HERE */
            byte[] buffer = new byte[fis.available()];

            while (fis.read(buffer) != -1) {
                compare = new String(buffer);
                if (compare.contains(encode)) {
                    flag = true;
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                return flag;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
4

2 回答 2

0

检查文件是否存在使用 -

File f = new File(filePathString);
if(f.exists()) { /* do something */ }
于 2013-10-28T21:06:40.840 回答
0

我想,根据您的快照,您需要的是FileNotFoundCase正确处理:

// ....
} catch (FileNotFoundException e) {
        Log.d("no settings for the user - assuming new user");
        flag = true;
}

顺便说一句,你需要修复你的 finally 块,以防之前的异常你fis可能是空的,所以为了避免NullPointerException你可能需要额外的检查:

if (fis != null) {
    fis.close();
}

更新

根据我对您的问题的理解,这是您可能需要的草图:

    // ... somewhere at startup after username/pass are given

    // check if file exists
    if (new File(FILENAME).isFile() == false) { // does not exist
        fos = new FileOutputStream(FILENAME); // will create 
                                              // file for you (not subfolders!)
        // write content to your file
        fos.close();
    }

    // by this point file exists for sure and filled with correct user data
    alreadyUser(userName);
于 2013-10-28T21:16:15.480 回答