【Android 开发教程】保存到内部存储设备

本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


SharedPreferences对象能够让你去保存一些“键值对”类型的数据,比如用户id,生日,性别,身份证号等等。但是,有的时候你需要去使用传统的文件系统去保存数据。例如你可能想要去保存一篇文章,而这篇文章要被展示在你的应用中。在Android系统中,你也可以使用java.io包去实现这个功能。

在Android系统中,第一种保存文件的方法是存储到内部设备。下面展示如何保存用书输入的字符串到内部存储设备。

1. 创建一个工程,Files。

2. main.xml中的代码。

<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Please enter some text" />

    <EditText
        android:id="@+id/txtText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickSave"
        android:text="Save" />

    <Button
        android:id="@+id/btnLoad"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickLoad"
        android:text="Load" />

</LinearLayout>
3. FilesActivity.java中的代码。

package net.manoel.Files;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import net.learn2develop.Files.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class FilesActivity extends Activity {
	EditText textBox;
	static final int READ_BLOCK_SIZE = 100;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		textBox = (EditText) findViewById(R.id.txtText1);

	}

	public void onClickSave(View view) {
		String str = textBox.getText().toString();
		try
		{
			FileOutputStream fOut =
					openFileOutput("textfile.txt",
							MODE_WORLD_READABLE);
                        
			OutputStreamWriter osw = new
					OutputStreamWriter(fOut);

			//---write the string to the file---
			osw.write(str);
			osw.flush(); 
			osw.close();

			//---display file saved message---
			Toast.makeText(getBaseContext(),
					"File saved successfully!",
					Toast.LENGTH_SHORT).show();

			//---clears the EditText---
			textBox.setText("");
		}
		catch (IOException ioe)
		{
			ioe.printStackTrace();
		}
	}

	public void onClickLoad(View view) {
		try
		{

			FileInputStream fIn = 
					openFileInput("textfile.txt");
			InputStreamReader isr = new 
					InputStreamReader(fIn);
            
			char[] inputBuffer = new char[READ_BLOCK_SIZE];
			String s = "";

			int charRead;
			while ((charRead = isr.read(inputBuffer))>0)
			{
				//---convert the chars to a String---
				String readString =
						String.copyValueOf(inputBuffer, 0,
								charRead);
				s += readString;

				inputBuffer = new char[READ_BLOCK_SIZE];
			}
			//---set the EditText to the text that has been 
			// read---
			textBox.setText(s);

			Toast.makeText(getBaseContext(),
					"File loaded successfully!",
					Toast.LENGTH_SHORT).show();
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}

}
4. 在模拟器上面调试。

5. 输入一些字符串,然后按Save按钮。

6. 如果保存成功,就是弹出“File saved successfully! ”字样。EditText中的字符串同时被清空。

7. 按Load键,刚刚的字符串又会重新出现,这也证明了刚刚的字符串被成功的保存到文件系统中了。


分析:

想要把字符串保存到一个文件里面,需要使用FileOutputStream这个类。openFileOutput()这个方法打开了一个可供写入的文件,同时也指定了相应的模式。在这个例子中,使用了MODE_WORLD_READABLE常量,意味着这个文件可以被其他的应用读。

			FileOutputStream fOut =
					openFileOutput("textfile.txt",
							MODE_WORLD_READABLE);
除了MODE_WORLD_READABLE常量,还有MODE_PRIVATE,MODE_APPEND,MODE_WORLD_WRITEABLE。

想要把字符串流转换成字节流,需要使用一个OutputStreamWriter类,初始化的时候需要传入一个FileOutputStream对象:

			OutputStreamWriter osw = new
					OutputStreamWriter(fOut);
调用write()接口去往文件里面写字符串,想要确保所有的字节都被写入的文件,需要调用flush()接口。最后,调用close()接口去关闭流。

			//---write the string to the file---
			osw.write(str);
			osw.flush(); 
			osw.close();
上面是写入的过程,读取的过程与之类似,我就不一一赘述了。大家请参考以下代码。

	public void onClickLoad(View view) {
		try
		{

			FileInputStream fIn = 
					openFileInput("textfile.txt");
			InputStreamReader isr = new 
					InputStreamReader(fIn);
            
			char[] inputBuffer = new char[READ_BLOCK_SIZE];
			String s = "";

			int charRead;
			while ((charRead = isr.read(inputBuffer))>0)
			{
				//---convert the chars to a String---
				String readString =
						String.copyValueOf(inputBuffer, 0,
								charRead);
				s += readString;

				inputBuffer = new char[READ_BLOCK_SIZE];
			}
			//---set the EditText to the text that has been 
			// read---
			textBox.setText(s);

			Toast.makeText(getBaseContext(),
					"File loaded successfully!",
					Toast.LENGTH_SHORT).show();
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}

最后,我们用DDMS工具去查看一下文件是否被成功地保存到内部存储设备上。

可以看到,文件被保存到data/data/net.manoel.Files/files路径下面。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值