Reading and writing your own, application-specific data files is nearly identical to what you might do in a desktop Java application. The key is to use openFileInput() and openFileOutput() on your Activity or other Context to get an InputStream and OutputStream, respectively. From that point forward, the process is not much different from using regular Java I/O logic:

• Wrap those streams as needed, such as using an InputStreamReader or OutputStreamWriter for text-based I/O.

• Read or write the data.

• Use close() to release the stream when done.

If two applications both try reading a notes.txt file via openFileInput(), they will each access their own edition of the file. If you need to have one file accessible from many places, you probably want to create a content provider, as will be described in Chapter 28.

Note that openFileInput() and openFileOutput() do not accept file paths (e.g., path/to/file.txt), just simple filenames.

The following code shows the layout for the world’s most trivial text editor, pulled from the Files/ReadWrite sample application available on the Apress Web site:

<?xml version='1.0' encoding='utf-8'?>

<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'

 android:layout_width='fill_parent'

 android:layout_height='fill_parent'

 android:orientation='vertical'>

 <Button android:id='@+id/close'

  android:layout_width='wrap_content'

  android:layout_height='wrap_content'

  android:text='Close' />

 <EditText

  android:id='@+id/editor'

  android:layout_width='fill_parent'

  android:layout_height='fill_parent'

  android:singleLine='false'

 />

</LinearLayout>

All we have here is a large text-editing widget with a Close button above it. The Java is only slightly more complicated:

package com.commonsware.android.files;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import java.io.BufferedReader;

import java.io.File;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

public class ReadWriteFileDemo extends Activity {

 private final static String NOTES = 'notes.txt';

 private EditText editor;

 @Override

 public void onCreate(Bundle icicle) {

  super.onCreate(icicle);

  setContentView(R.layout.main);

  editor = (EditText)findViewById(R.id.editor);

  Button btn = (Button)findViewById(R.id.close);

  btn.setOnClickListener(new Button.OnClickListener() {

   public void onClick(View v) {

    finish();

   }

  });

 }

 public void onResume() {

  super.onResume();

  try {

   InputStream in = openFileInput(NOTES);

   if (in != null) {

    InputStreamReader tmp = new InputStreamReader(in);

    BufferedReader reader = new BufferedReader(tmp);

    String str;

    StringBuffer buf = new StringBuffer();

    while ((str = reader.readLine()) ! = null) {

     buf.append(str+' ');

    }

    in.close();

    editor.setText(buf.toString());

   }

  } catch (java.io.FileNotFoundException e) {

   // that's OK, we probably haven't created it yet

  } catch (Throwable t) {

   Toast.makeText(this, 'Exception: ' + t.toString(), 2000).show();

  }

 }

 public void onPause() {

  super.onPause();

Вы читаете Beginning Android
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату