简体   繁体   中英

Unable to read/write to file in android

I'm trying to get my app to write text into a text file from an EditText and read from it into a TextView. It never updated the TextView earlier and now the app is crashing. Any advise would be very appreciated!

public class MainActivity extends Activity implements OnClickListener {

String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button rea = (Button) findViewById(R.id.reads1);   
    rea.setOnClickListener(this);

    Button ap = (Button) findViewById(R.id.appends1);   
    ap.setOnClickListener(this);

}

private void toast(String text)
{
    Context context = getApplicationContext();
    Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
    toast.show();
}

@SuppressWarnings("resource")
@Override
public void onClick(View v) {

    TextView tv=(TextView)findViewById(R.id.textView1);
    EditText et=(EditText)findViewById(R.id.editText1); 

    switch(v.getId()) {
    case R.id.reads1:

           try
            {
               FileInputStream fis = new FileInputStream(file);
               BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
               String in;
               StringBuffer stringBuffer = new StringBuffer();                
               while ((in = bfr.readLine()) != null) {
                   stringBuffer.append(in + "\n");
               }
               tv.setText(stringBuffer.toString());
                toast("File successfully loaded.");

            }
            catch (Exception ex)
            {
                toast("Error loading file: " + ex.getLocalizedMessage());

            }

        break;

    case R.id.appends1:

        String txt=et.getText().toString(); 

         try
            {
             FileWriter writer = new FileWriter(file);
            writer.write(txt); 
            writer.flush();
            writer.close();

                toast("File successfully saved.");
            }
            catch (Exception ex)
            {
                toast("Error saving file: " + ex.getLocalizedMessage());
            }

        break;

  }

}

}

Get the sdcard directory using Environment.getExternalStorageDirectory() . Try changing this line in you code:

String file = "sdcard/CSCI598.txt";

With:

String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";

Also, as @Yahya mentioned make sure you have this permission in your android manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If this doesn't work. Try reading the file like this:

FileReader fr = new FileReader(file);
BufferedReader inputReader = new BufferedReader(fr);

Then use your while loop as it is right now.

Write the file like this

FileWriter out = new FileWriter(file, true);
 out.write(txt + "\n");
 out.close();

Provide crash log.

  1. Have you given sdcard read write permission in your manifest xml file.

< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >< /uses-permission >

  1. Instead of using hard coded path like String file = "sdcard/CSCI598.txt"; use below

    String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";

  2. As you are using emulator have have you alot sd card space while creating AVD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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