【问题标题】:Android FileInputStream Code causes CrashAndroid FileInputStream 代码导致崩溃
【发布时间】:2012-05-26 04:15:03
【问题描述】:

我已经解决了自己的问题,但我不知道为什么我的第一次尝试没有奏效,我希望有人能告诉我原因。 我也希望有人能告诉我我的最终解决方案是否“好”(我的意思是,它是否有效)?

这是我第一次尝试读取我之前创建的输入文件:

private byte[] mInputData;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_view);

    Intent myIntent = getIntent();

    mFilename = myIntent.getStringExtra("FILENAME");
    mSplitSeq = myIntent.getStringExtra("SPLIT_SEQ");

    try {
        fis = openFileInput(mFilename);
        fis.read(mInputData);
        fis.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

这是我在网上找到的确实有效的东西:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_view);

    Intent myIntent = getIntent();

    mFilename = myIntent.getStringExtra("FILENAME");
    mSplitSeq = myIntent.getStringExtra("SPLIT_SEQ");

    try {
        fis = openFileInput(mFilename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
        String line = null, input="";
        while ((line = reader.readLine()) != null)
            mTimeStr += line;
        reader.close();
        fis.close();
        //fis.read(mInputData);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

我在第一次实现时收到的错误是调用 fis.read(mInputData) 函数时出现 NullPointerException。

【问题讨论】:

    标签: android bufferedreader fileinputstream


    【解决方案1】:

    我很确定这是因为 mInputData 从未初始化。你需要像mInputData = new byte[1000]; 这样的一行。相反,您是在告诉 read() 将数据提供给等于 null 的引用,即 NullPointerException。

    【讨论】:

    • 啊,有道理。有没有办法使字节数组动态化?我猜第二种解决方案是动态的,但如果能够调用一个读取所有内容而不循环的读取函数会很好。
    • 您可以使用int byteArraySize = new File(mFileName).length()。 File 上的 length 方法以字节为单位返回大小。
    • 您发现 BufferedReader 方法有什么问题吗?或者任何会特别低效的东西?
    • 我认为使用 BufferedReader 是读取输入的好方法,我会坚持使用这种方法。但是,请查看此问题的公认答案:stackoverflow.com/questions/2492076/… 您可能希望使用 StringBuilder 而不是附加到 String。
    • 谢谢你,这是一本好书,我现在理解(并且正在使用)StringBuilder!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多