简体   繁体   English

当使用openFileInput找不到文件时,如何防止android应用崩溃

[英]How to prevent android app from crashing when a file has not been found using openFileInput

I want to react to a situation that no file has been found using FileInputStream. 我想对使用FileInputStream找不到文件的情况做出反应。 When i ran an app that loads a file that doesn't exist it opens an android popup with force close. 当我运行的应用程序加载了一个不存在的文件时,它会强制关闭以打开android弹出窗口。 I would like to react to the situation by changing a text in a text view and saying that the file has not been found. 我想通过在文本视图中更改文本并说未找到文件来对这种情况做出反应。 i tried changing the exceptions to change a text view and show that a file has not been found and the app still crashes. 我尝试更改异常以更改文本视图,并显示未找到文件,并且应用程序仍然崩溃。

Here is the piece of code: 这是一段代码:

 FileInputStream fis = null;
    String collected = null;
    try {
        fis = openFileInput("test");
        byte[] dataArray = new byte[fis.available()];
        while (fis.read(dataArray) != -1){
            collected = new String(dataArray);
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block

        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    tv.setText(collected);

To ensure that an Android application does not force-close, your options are: a) do not do anything that will cause an exception, b) catch your exception with your own try/catch block, c) install an application level uncaught exception handler. 为确保Android应用程序不会强制关闭,您的选择是:a)不做任何会导致异常的事情,b)用自己的try / catch块捕获异常,c)安装应用程序级未捕获的异常处理程序。 Option a is not too feasible, c is not very helpful, and based on your code snippet you seem to be trying b -- however there appears to be another exception that you're not catching with this. 选项a不太可行,c并不是很有用,根据您的代码片段,您似乎正在尝试b-但是,似乎还有另一个例外,您对此并不了解。 The contents of logcat will tell you what exception, and the stack trace will lead to a point in your code which needs the try/catch. logcat的内容将告诉您什么异常,并且堆栈跟踪将导致代码中需要try / catch的一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM