Android学习笔记<20140113> Internal Storage

来源:互联网 发布:js求数组最大值和下标 编辑:程序博客网 时间:2024/06/08 10:43
  Android为应用程序的存储提供了五种方式:1.Shared Preferences; 2.Internal Storage; 3. External Storage; 4. SQLite Database; 5.Network Connection。
  Internal Storage 把数据存储在设备内部存储器上,存储在/data/data/<package name>/files目录下。默认情况下在这里存储的数据为应用程序的私有数据,其它应用程序不能访问。卸载应用程序后,内部存储器的/data/data/<package name>目录及其下子目录和文件一同被删除。
  向内部存储器中创建一个私有文件并向其中写入数据,使用以下方法:1. 调用openFileOutput(String fileName, int mode)方法,若fileName对应的文件存在,就打开该文件,若不存在,并以mode权限创建该文件并打开,该方法返回一个指向fileName对应文件的FileOutputStream,使用这个FileOutputStream可向文件中写入数据。2. 调用FileOutputStream对象的write()方法向文件中写入数据。3. 调用FileOutputStream对象的close()方法关闭文件写入流。
  例:向内部存储器中写入一个名为"my_first_inner_file.txt"的文件后,会在内部存储器的/data/data/<package name>/files/目录下生成"my_first_inner_file.txt"文件,如下图所示:
  
  读取内部存储器中私有文件的数据,使用以下方法:1. 调用openFileInputStream(String fileName)方法打开内部存储器中fileName对应的文件,若该文件存在,该方法返回一个指向fileName文件的FileInputStream对象。2. 调用FileInputStream对象的read()方法读取fileName文件中的内容。3. 调用FileInputStream对象的close()方法关闭文件读取流。
  如果想在编译时就在应用程序中保存一个不允许修改的文件,就把这个文件保存在/res/raw/目录下。在程序中打开这个文件可以调用openRawResource(int id)方法, 里面的参数id表示R.raw.<file name>,这个方法打开后会返回一个InputStream,使用它可以读取这个文件。这个文件不能被执行写入操作。
  如果有缓存文件需要保存,而这些文件并不需要永久保存,可以调用getCacheDir()方法,该方法执行后会在内部存储器的/data/data/<package name>/目录下创建一个名为cache/的空目录(或打开cache/目录),并返回一个File对象指向这个(空)文件夹。在这个cache/目录下,可以保存缓存文件,当设备的内部存储器空间不够用时,系统会自动删除一部分cache/目录下的缓存文件,但为了保证系统运行效率,应该手动对cache/目录的大小进行控制,如控制它不能大于1M。当用户卸载应用程序时,cache/目录会连同一起被删除。
  例:调用getCacheDir()方法,该方法执行后会在内部存储器的/data/data/<package name>/目录下创建一个名为cache/的空目录。如下图:
  
  
  示例程序:
  1. 向内部存储器中写入数据;
  2. 读取内部存储器中的数据;
  3. 在内部存储器中创建缓存目录,并向其中新建文件、写入数据。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <LinearLayout         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <EditText             android:id="@+id/edit_message"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:hint="@string/input_message"/>        <Button             android:id="@+id/button_write"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/write"/>    </LinearLayout>        <View         android:layout_width="match_parent"        android:layout_height="1dp"        android:background="#999999"/>        <TextView         android:id="@+id/text_read"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:padding="8dp"        android:background="#ddddee"/>        <Button         android:id="@+id/button_read"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/read"/>        <Button         android:id="@+id/button_cache"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/cache"/></LinearLayout>
<pre code_snippet_id="154252" snippet_file_name="blog_20140113_2_2753638" name="code" class="java">package com.example.demo0113innerstorage;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintStream;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;import android.widget.Toast;/** * 1. 该方法直接保存数据在设备的内部存储器上,文件保存在路径:/data/data/<package name>/files/目录下。默认情况下,保存在这里的数据是本应用程序私有的 *     , 其它应用程序不能访问,当用户卸载本应用程序后,这些数据会一起被删除。 * 2. To create and write a private file to the internal storage: *     Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream. *     Write to the file with write(). *     Close the stream with close(). * 3. To read a file from internal storage: *     Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. *     Read bytes from the file with read(). *     Then close the stream with close(). * 4. 如果想在编译时就在应用程序中保存一个不允许更改的文件,就把这个文件保存在路径/res/raw/目录下。在程序中打开这个文件可以调用openRawResource(int id)方法 *     , 里面的参数id表示R.raw.<file name>,这个方法打开后会返回一个InputStream,使用它可以读取这个文件,但是这个文件不能被执行写入操作。 * 5。 如果有缓存文件需要保存,这些文件并不需要永久保存,可以调用getCacheDir()方法,该方法执行后会在内部存储器的/data/data/<package name>/目录下创建 *     一个名为cache/的空目录,并返回一个File对象指向这个空文件夹。在这个cache/目录下,可以保存缓存文件,当设备的内部存储器空间不够用时,系统会自动删除一部分cache/ *     目录下的缓存文件,但为了保证系统运行效率,应该手动对cache/目录的大小进行控制,如控制它不能大于1M。当用户卸载应用程序时,cache/目录会连同一起被删除。 * */public class MainActivity extends Activity {final String FILE_NAME = "my_first_inner_file.txt";private EditText editMessage;private TextView textRead;private Button buttonWrite, buttonRead, buttonCache;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);editMessage = (EditText) findViewById(R.id.edit_message);textRead = (TextView) findViewById(R.id.text_read);buttonWrite = (Button) findViewById(R.id.button_write);buttonRead = (Button) findViewById(R.id.button_read);buttonCache = (Button) findViewById(R.id.button_cache);buttonWrite.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String message = editMessage.getText().toString();write(message);editMessage.setText("");}});buttonRead.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {textRead.setText(read());}});buttonCache.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {File cacheFile = getCacheDir();// 执行该方法后,会在/data/data/<package name>下创建一个空/cache目录或打开/cache目录,// 并返回一个指向/cache目录的File对象。File cacheFile1 = new File(cacheFile.getAbsolutePath() + "/cacheFile1.txt");// 在/cache目录下创建或打开一个名为...的文件try {FileOutputStream fout = new FileOutputStream(cacheFile1);// 获得文件的输出流try {fout.write("message1".getBytes());// 向文件中写入数据fout.close();// 关闭文件输出流} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();}}});}private String read() {try {FileInputStream fis = openFileInput(FILE_NAME);StringBuilder stringBuiler = new StringBuilder("");byte[] buffer = new byte[1024];int hasRead = 0;try {while ((hasRead = fis.read(buffer)) > 0) {String msg = new String(buffer, 0, hasRead);stringBuiler.append(msg);}try {fis.close();} catch (IOException e) {e.printStackTrace();}return stringBuiler.toString();} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();Toast.makeText(this, "file not found.", Toast.LENGTH_SHORT).show();}return null;}private void write(String message) {try {FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);PrintStream ps = new PrintStream(fos);ps.println(message);ps.close();try {fos.close();} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();}}}
                                             
0 0
原创粉丝点击