我该如何处理FileNotFoundException?

时间:2016-04-29 00:41:30

标签: android

最近

我尝试A.txt文件阅读内容。

但是如果我的设备没有a.txt,则会发生FileNotFoundException

所以我想如果我的设备没有a.txt,我该如何继续?

String path = "/sdcard/Download";
    String textName = "a.txt";

    String serverVersion = null;
    BufferedReader br = null;
    try {
        br = BufferedReaderFactory.create(path, textName);

        StringBuilder contentGetter = new StringBuilder();
        while ((serverVersion = br.readLine()) != null) {

            serverVersion = serverVersion.trim().toLowerCase();
            contentGetter.append('\n' + serverVersion);
            Log.d(TAG, " myServerVersion = " + serverVersion);
            break;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:1)

你可以在try / catch之前简单地创建一个变量,如

boolean isFileFound = false;

所以,在尝试的最后,你设置了isFileFound = true 像:

String path = "/sdcard/Download";
    String textName = "a.txt";

    boolean isFileFound = false;

    String serverVersion = null;
    BufferedReader br = null;
    try {
        br = BufferedReaderFactory.create(path, textName);

        StringBuilder contentGetter = new StringBuilder();
        while ((serverVersion = br.readLine()) != null) {

            serverVersion = serverVersion.trim().toLowerCase();
            contentGetter.append('\n' + serverVersion);
            Log.d(TAG, " myServerVersion = " + serverVersion);
            break;
        }
        isFileFound = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (!isFileFound){ // This is equals to if(isFileFound != null)
        //Do some message here, like:
        Toast toast = Toast.makeText(context, "File not found", Toast.LENGTH_SHORT).show();
    }

答案 1 :(得分:0)

看起来您已经在处理异常了。如果没有文件,您的代码将按计划继续。在try / catch块之后,您应该检查9 9,如果它返回true,您就知道没有从文件中读取serverVersion。