Android文件 ——保存到内部存储设备

来源:互联网 发布:淘宝如何发布宝贝详情 编辑:程序博客网 时间:2024/06/05 07:32
SharedPreferences对象能够让你去保存一些“键值对”类型的数据,比如用户id,生日,性别,身份证号等等。但是,有的时候你需要去使用传统的文件系统去保存数据。例如你可能想要去保存一篇文章,而这篇文章要被展示在你的应用中。在Android系统中,你也可以使用java.io包去实现这个功能。


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


1. 创建一个工程,Files。


2. main.xml中的代码。


[html] view plaincopy
<?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中的代码。
[java] view plaincopy
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常量,意味着这个文件可以被其他的应用读。


[java] view plaincopy
FileOutputStream fOut =  
        openFileOutput("textfile.txt",  
                MODE_WORLD_READABLE);  
除了MODE_WORLD_READABLE常量,还有MODE_PRIVATE,MODE_APPEND,MODE_WORLD_WRITEABLE。
想要把字符串流转换成字节流,需要使用一个OutputStreamWriter类,初始化的时候需要传入一个FileOutputStream对象:


[java] view plaincopy
OutputStreamWriter osw = new  
        OutputStreamWriter(fOut);  
调用write()接口去往文件里面写字符串,想要确保所有的字节都被写入的文件,需要调用flush()接口。最后,调用close()接口去关闭流。
[java] view plaincopy
//---write the string to the file---  
osw.write(str);  
osw.flush();   
osw.close();  
上面是写入的过程,读取的过程与之类似,我就不一一赘述了。大家请参考以下代码。
[java] view plaincopy
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路径下面。

原创粉丝点击