android 文件输入流崩溃

发布于 2024-11-24 15:26:34 字数 5493 浏览 2 评论 0原文

我是一名业余程序员,从事 Android 开发。我现在只是想了解基础知识,但我遇到了错误,我不知道为什么。

我正在创建一个具有保存和加载按钮的活动,它使用 fileOutputStream 和 fileInputStream 来完成此任务。

我遇到的问题是,如果我第一次使用该活动时点击加载按钮,我的应用程序就会崩溃。如果文件尚未创建,任何人都可以帮助我如何跳过加载部分吗?我应该在 if 语句中使用什么。

非常感谢,这是我的代码:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class InternalData extends Activity implements OnClickListener {

    String FILENAME = "InternalString";
    EditText sharedData;
    TextView dataResults;
    FileOutputStream fos;
    String d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sharedpreferences);
        Button save = (Button) findViewById(R.id.bSave);
        Button load = (Button) findViewById(R.id.bLoad);
        sharedData = (EditText) findViewById(R.id.etSharedPrefs);
        dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
        save.setOnClickListener(this);
        load.setOnClickListener(this);
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.bSave:
            d = sharedData.getText().toString();

            try {

                fos.write(d.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            break;
        case R.id.bLoad:
            FileInputStream fis = null;
            try {
                if (openFileInput(FILENAME) != null){
                fis = openFileInput(FILENAME);
                byte[] data = new byte[fis.available()];
                while(fis.read(data) != -1){
                    String readData = new String(data);
                    dataResults.setText(readData);
                }}
            } 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();
                }
            }

            break;
        }
    }
}

感谢卢卡斯的帮助,我已经更新了我的代码,我想知道你是否可以检查一下以确保我正确使用 AsyncTask。再次感谢!

public class InternalData extends Activity implements OnClickListener {

String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sharedpreferences);
    Button save = (Button) findViewById(R.id.bSave);
    Button load = (Button) findViewById(R.id.bLoad);
    sharedData = (EditText) findViewById(R.id.etSharedPrefs);
    dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
    save.setOnClickListener(this);
    load.setOnClickListener(this);

}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bSave:
        d = sharedData.getText().toString();

        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(d.getBytes());
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        break;
    case R.id.bLoad:

            AsyncTask<String, Integer, String> dat = new loadInternalData().execute(FILENAME);  

        break;
    }
}

public class loadInternalData extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        FileInputStream fis = null;
        String collected = null;
        try {
            fis = openFileInput(FILENAME);
            byte[] data = new byte[fis.available()];
            while (fis.read(data) != -1){
                collected = new String(data);

            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                return collected;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return collected;
    }
     @Override
     protected void onPostExecute( String result ) 
     {
             super.onPostExecute(result);
             Log.i( "InteralStorage", "onPostExecute(): " + result );
             dataResults.setText( result );

     }
}

}

I am an amateur programmer developing for android. I am just trying get the basics down right now, but I am having an error and I don't know why.

I am creating a activity that has a save and a load button, which using the fileOutputStream and fileInputStream to achieve this task.

The problem I am having is if I hit the load button the first time I use the activity, my application crashes. Can anyone help me with how to skip the load section if the file hasn't been created yet? What should I use within my if statement.

Thanks a ton, here is my code:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class InternalData extends Activity implements OnClickListener {

    String FILENAME = "InternalString";
    EditText sharedData;
    TextView dataResults;
    FileOutputStream fos;
    String d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sharedpreferences);
        Button save = (Button) findViewById(R.id.bSave);
        Button load = (Button) findViewById(R.id.bLoad);
        sharedData = (EditText) findViewById(R.id.etSharedPrefs);
        dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
        save.setOnClickListener(this);
        load.setOnClickListener(this);
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.bSave:
            d = sharedData.getText().toString();

            try {

                fos.write(d.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            break;
        case R.id.bLoad:
            FileInputStream fis = null;
            try {
                if (openFileInput(FILENAME) != null){
                fis = openFileInput(FILENAME);
                byte[] data = new byte[fis.available()];
                while(fis.read(data) != -1){
                    String readData = new String(data);
                    dataResults.setText(readData);
                }}
            } 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();
                }
            }

            break;
        }
    }
}

Thanks for the help Lukas, I have updated my code, and I was wondering if you could look it over to make sure I am using the AsyncTask properly. Thanks again!

public class InternalData extends Activity implements OnClickListener {

String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sharedpreferences);
    Button save = (Button) findViewById(R.id.bSave);
    Button load = (Button) findViewById(R.id.bLoad);
    sharedData = (EditText) findViewById(R.id.etSharedPrefs);
    dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
    save.setOnClickListener(this);
    load.setOnClickListener(this);

}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bSave:
        d = sharedData.getText().toString();

        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(d.getBytes());
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        break;
    case R.id.bLoad:

            AsyncTask<String, Integer, String> dat = new loadInternalData().execute(FILENAME);  

        break;
    }
}

public class loadInternalData extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        FileInputStream fis = null;
        String collected = null;
        try {
            fis = openFileInput(FILENAME);
            byte[] data = new byte[fis.available()];
            while (fis.read(data) != -1){
                collected = new String(data);

            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                return collected;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return collected;
    }
     @Override
     protected void onPostExecute( String result ) 
     {
             super.onPostExecute(result);
             Log.i( "InteralStorage", "onPostExecute(): " + result );
             dataResults.setText( result );

     }
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹤仙姿 2024-12-01 15:26:34

您正在调用 openFileInput 两次。只需调用一次即可。

而不是这样

if (openFileInput(FILENAME) != null){
    fis = openFileInput(FILENAME);
}

做:

fis = openFileInput(FILENAME);
if (fis != null) {
    // Read file
}

You are calling openFileInput twice. Just call it once.

Instead of this

if (openFileInput(FILENAME) != null){
    fis = openFileInput(FILENAME);
}

Do this:

fis = openFileInput(FILENAME);
if (fis != null) {
    // Read file
}
半﹌身腐败 2024-12-01 15:26:34

如果您在 UI 线程上执行某些操作,则时间不应超过 5 秒或 ANR 将被触发。

如果您想做的事情可能需要比这 5 秒更长的时间,您需要在 服务AsyncTask

另外,如果您的应用程序被强制关闭并且您不知道原因,您应该始终查看 LogCat 输出,可以在 Eclipse 中显示。另外,您应该将其包含在您在这里提出的每个问题中(关于 Android)。

If you execute something on the UI-Thread, it shouldn't take longer then 5 seconds or an ANR will be triggered.

If you want to do something that might take longer then those 5 seconds, you'll want to do it in a Service or an AsyncTask.

Also, if your App gets force closed and you don't know why, you should always have a look at the LogCat output which can be shown in Eclipse. Also, you should include it with every question you ask here (about Android).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文