Android 简明教程

Android - Internal Storage

Android 为应用程序提供了多种存储类型以存储其数据。这些存储位置为共享首选项、内部和外部存储、SQLite 存储以及通过网络连接的存储。

Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, SQLite storage, and storage via network connection.

在本章中,我们将研究内部存储。内部存储是将私有数据存储在设备内存中的存储。

In this chapter we are going to look at the internal storage. Internal storage is the storage of the private data on the device memory.

默认情况下,这些文件是私有的,只能被您的应用程序访问,在用户删除您的应用程序时会被删除。

By default these files are private and are accessed by only your application and get deleted , when user delete your application.

Writing file

要使用内部存储将一些数据写入文件,请使用文件名和模式调用 openFileOutput() 方法。模式可以是私有的、公共的等。其语法如下 −

In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below −

FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);

该方法 openFileOutput() 返回 FileOutputStream 的一个实例。因此,您在 FileInputStream 的对象中接收它。之后,您调用 write 方法将数据写入文件。其语法如下 −

The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below −

String str = "data";
fOut.write(str.getBytes());
fOut.close();

Reading file

要读取刚刚创建的文件,请使用文件名调用 openFileInput() 方法。它返回 FileInputStream 的一个实例。其语法如下 −

In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its syntax is given below −

FileInputStream fin = openFileInput(file);

之后,您可以调用 read 方法以一次从文件中读取一个字符,然后打印它。其语法如下 −

After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below −

int c;
String temp="";
while( (c = fin.read()) != -1){
   temp = temp + Character.toString((char)c);
}

//string temp contains all the data of the file.
fin.close();

除了 write 和 close 方法外, FileOutputStream 类还提供了其他方法,可以更好地写入文件。这些方法如下列出 −

Apart from the the methods of write and close, there are other methods provided by the FileOutputStream class for better writing files. These methods are listed below −

Sr.No

Method & description

1

FileOutputStream(File file, boolean append) This method constructs a new FileOutputStream that writes to file.

2

getChannel() This method returns a write-only FileChannel that shares its position with this stream

3

getFD() This method returns the underlying file descriptor

4

write(byte[] buffer, int byteOffset, int byteCount) This method Writes count bytes from the byte array buffer starting at position offset to this stream

除了 read 和 close 方法外, FileInputStream 类还提供其他方法以更好地读取文件。以下是所列方法 −

Apart from the the methods of read and close, there are other methods provided by the FileInputStream class for better reading files. These methods are listed below −

Sr.No

Method & description

1

available() This method returns an estimated number of bytes that can be read or skipped without blocking for more input

2

getChannel() This method returns a read-only FileChannel that shares its position with this stream

3

getFD() This method returns the underlying file descriptor

4

read(byte[] buffer, int byteOffset, int byteCount) This method reads at most length bytes from this stream and stores them in the byte array b starting at offset

Example

以下是使用内部存储来存储和读取文件的一个示例演示。它创建了一个基本存储应用程序,允许您从内部存储中读取和写入。

Here is an example demonstrating the use of internal storage to store and read files. It creates a basic storage application that allows you to read and write from internal storage.

要试验此示例,您可以在实际设备或模拟器上运行它。

To experiment with this example, you can run this on an actual device or in an emulator.

Steps

Description

1

You will use Android Studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add necessary code.

3

Modify the res/layout/activity_main to add respective XML components

4

Run the application and choose a running android device and install the application on it and verify the results

以下是修改的主活动文件 src/MainActivity.java 的内容。

Following is the content of the modified main activity file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends Activity  {
   Button b1,b2;
   TextView tv;
   EditText ed1;

   String data;
   private String file = "mydata";

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

      b1=(Button)findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);

      ed1=(EditText)findViewById(R.id.editText);
      tv=(TextView)findViewById(R.id.textView2);
      b1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {
            data=ed1.getText().toString();
            try {
               FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
               fOut.write(data.getBytes());
               fOut.close();
               Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
            }
            catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
         }
      });

      b2.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {
            try {
               FileInputStream fin = openFileInput(file);
               int c;
               String temp="";
               while( (c = fin.read()) != -1){
                  temp = temp + Character.toString((char)c);
               }
               tv.setText(temp);
               Toast.makeText(getBaseContext(),"file read",Toast.LENGTH_SHORT).show();
            }
            catch(Exception e){
            }
         }
      });
   }
}

以下是修改后的 xml res/layout/activity_main.xml 内容。

Following is the modified content of the xml res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView android:text="Internal storage" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Save"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Text"
      android:focusable="true"
      android:textColorHighlight="#ff7eff15"
      android:textColorHint="#ffff25e6"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:layout_marginTop="42dp"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="load"
      android:id="@+id/button2"
      android:layout_alignTop="@+id/button"
      android:layout_alignRight="@+id/editText"
      android:layout_alignEnd="@+id/editText" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Read"
      android:id="@+id/textView2"
      android:layout_below="@+id/editText"
      android:layout_toLeftOf="@+id/button2"
      android:layout_toStartOf="@+id/button2"
      android:textColor="#ff5bff1f"
      android:textSize="25dp" />

</RelativeLayout>

以下是 res/values/string.xml 的内容。

Following is the content of the res/values/string.xml.

<resources>
   <string name="app_name">My Application</string>
</resources>

下面是 AndroidManifest.xml 文件的内容。

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>

我们尝试运行刚才修改的存储应用程序。我假设您在进行环境设置时已创建您的 AVD 。要从 Android Studio 运行应用程序,请打开项目的一个活动文件,然后从工具栏中单击运行图标。Android Studio 将应用程序安装在您的 AVD 上并启动它,如果您的设置和应用程序一切正常,那么它将显示以下模拟窗口 −

Let’s try to run our Storage application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −

internal storage

现在,您需要做的就是在该字段中输入任何文本。例如,我输入一些文本。按保存按钮。以下通知将显示在您的 AVD 中 −

Now what you need to do is to enter any text in the field. For example , i have entered some text. Press the save button. The following notification would appear in you AVD −

internal storage save

现在,在您按下加载按钮时,该应用程序将读取该文件并显示数据。对于我们来说,将返回以下数据 −

Now when you press the load button, the application will read the file , and display the data. In case of our, following data would be returned −

internal storage read

请注意,您可以通过切换至 DDMS 选项卡来查看此文件。在 DDMS 中,选择文件浏览器并导航此路径。

Note you can actually view this file by switching to DDMS tab. In DDMS , select file explorer and navigate this path.

tools>android>android device Monitor

这已在下面的图片中显示过。

This has also been shown in the image below.

ddms internal