android实例教程_Android内部存储示例教程

android实例教程

Today we will look into android internal storage. Android offers a few structured ways to store data. These include

今天,我们将研究android内部存储。 Android提供了一些结构化的方式来存储数据 。 这些包括

In this tutorial we are going to look into the saving and reading data into files using Android Internal Storage.

在本教程中,我们将研究如何使用Android Internal Storage将数据保存和读取到文件中。

Android内部存储 (Android Internal Storage)

Android Internal storage is the storage of the private data on the device memory. By default, saving and loading files to the internal storage are private to the application and other applications will not have access to these files. When the user uninstalls the applications the internal stored files associated with the application are also removed. However, note that some users root their Android phones, gaining superuser access. These users will be able to read and write whatever files they wish.

Android内部存储是设备内存中私有数据的存储。 默认情况下,将文件保存和加载到内部存储是应用程序专用的,其他应用程序将无法访问这些文件。 当用户卸载应用程序时,与该应用程序关联的内部存储文件也将被删除。 但是,请注意,某些用户会扎根其Android手机,从而获得超级用户访问权限。 这些用户将能够读取和写入所需的任何文件。

在Android内部存储中读取和写入文本文件 (Reading and Writing Text File in Android Internal Storage)

Android offers openFileInput and openFileOutput from the Java I/O classes to modify reading and writing streams from and to local files.

Android从Java I / O类提供openFileInputopenFileOutput ,以修改本地文件之间的读写流。

  • openFileOutput(): This method is used to create and save a file. Its syntax is given below:
    FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);

    The method openFileOutput() returns an instance of FileOutputStream. After that we can call write method to write data on the file. Its syntax is given below:

    openFileOutput() :此方法用于创建和保存文件。 其语法如下:
    FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);

    方法openFileOutput()返回FileOutputStream一个实例。 之后,我们可以调用write方法在文件上写入数据。 其语法如下:

  • openFileInput(): This method is used to open a file and read it. It returns an instance of FileInputStream. Its syntax is given below:
    FileInputStream fin = openFileInput(file);

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

    In the above code, string temp contains all the data of the file.

    openFileInput() :此方法用于打开文件并读取它。 它返回FileInputStream的实例。 其语法如下:
    FileInputStream fin = openFileInput(file);

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

    在上面的代码中,字符串temp包含文件的所有数据。

  • Note that these methods do not accept file paths (e.g. path/to/file.txt), they just take simple file names.

    请注意,这些方法不接受文件路径(例如path / to / file.txt),它们仅使用简单的文件名。

Android内部存储项目结构 (Android Internal Storage Project Structure)

Android内部存储示例代码 (Android Internal Storage Example Code)

The xml layout contains an EditText to write data to the file and a Write Button and Read Button. Note that the onClick methods are defined in the xml file only as shown below:

xml布局包含用于将数据写入文件的EditText以及“写入按钮”和“读取按钮”。 请注意,仅在xml文件中定义onClick方法,如下所示:

activity_main.xml

activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:padding="5dp"
        android:text="Android Read and Write Text from/to a File"
        android:textStyle="bold"
        android:textSize="28sp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:minLines="5"
        android:layout_margin="5dp">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write Text into File"
        android:onClick="WriteBtn"
        android:layout_alignTop="@+id/button2"
        android:layout_alignRight="@+id/editText1"
        android:layout_alignEnd="@+id/editText1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read Text From file"
        android:onClick="ReadBtn"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignStart="@+id/editText1" />

</RelativeLayout>

The MainActivity contains the implementation of the reading and writing to files as it was explained above.

MainActivity包含对文件进行读写的实现,如上所述。

package com.journaldev.internalstorage;


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

public class MainActivity extends Activity {

    EditText textmsg;
    static final int READ_BLOCK_SIZE = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textmsg=(EditText)findViewById(R.id.editText1);
    }

    // write text to file
    public void WriteBtn(View v) {
        // add-write text into file
        try {
            FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write(textmsg.getText().toString());
            outputWriter.close();

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

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Read text from file
    public void ReadBtn(View v) {
        //reading text from file
        try {
            FileInputStream fileIn=openFileInput("mytextfile.txt");
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                // char to string conversion
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();
            textmsg.setText(s);
            

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Here, a toast is displayed when data is successfully written into the internal storage and the data is displayed in the EditText itself on reading the data from the file.

在此,当成功将数据写入内部存储器时,将显示祝酒词,并且在从文件中读取数据时,数据将显示在EditText本身中。

The image shown below is the output of the project. The image depicts text being written to the internal storage and on clicking Read it displays back the text in the same EditText.

下图是项目的输出。 该图像描述了写入内部存储器的文本,单击“读取”后,它将在同一EditText中显示文本。

文件在哪里? (Where is the file located?)

To actually view the file open the Android Device Monitor from Tools->Android->Android Device Monitor.
The file is present in the folder data->data->{package name}->files as shown in the images below:

android file storage, internal storage, Android OpenFileOutput

要实际查看文件,请从工具-> Android-> Android设备监视器中打开Android设备监视器。
该文件位于文件夹data-> data-> {package name}-> files中,如下图所示:

The file “mytextfile.txt” is found in the package name of the project i.e. com.journaldev.internalstorage as shown below:

在项目的程序包名称com.journaldev.internalstorage中可以找到文件“ mytextfile.txt” ,如下所示:

android file storage, internal storage, Android OpenFileOutput

Download the final project for android internal storage example from below link.


从下面的链接下载android内部存储示例的最终项目。

翻译自: https://www.journaldev.com/9383/android-internal-storage-example-tutorial

android实例教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值