English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detaillierte Erklärung der Dateioperationen in Android und einfache Beispiele

 Detaillierte Erklärung der Dateioperationen von Android

Die Dateioperationen von Android im Endeffekt sind die Verarbeitung der Dateioperationen von Java. Daher ist die Dateioperation von Android ein Leichtes, wenn man sich mit den io-Dateioperationen von Java auskennt. Na gut, also genug Gesprochen, lasst uns zum heutigen Thema übergehen.

Beginnen wir mit einem kleinen Projekt, um uns einzuführen.

Zunächst ist eine Layout-Datei, das ist relativ einfach, also fangen wir direkt mit dem Code an.

<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" >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="文件名称" />
  <EditText 
    android:id="@"+id/et_filename"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="file name"
    />
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="文件内容" />
  <EditText 
    android:id="@"+id/et_filecontent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lines="7"
    android:hint="file content"
    />
  <Button 
    android:id="@"+id/btn_save"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="toSave"
    android:text="Save"
    />
  <Button 
    android:id="@"+id/btn_get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="getFile"
    android:text="Get"
    />
</LinearLayout>

Dann ist unser Hauptfenster-Datei in Java. Fahren wir mit dem Code fort.

package com.mark.storage;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mark.service.FileService;
public class MainActivity extends Activity {
  private EditText mEt_filename, mEt_filecontent;
  private Button mBtn_save;
  private void init(){
    mEt_filecontent = (EditText) findViewById(R.id.et_filecontent);
    mEt_filename = (EditText) findViewById(R.id.et_filename);
    mBtn_save = (Button) findViewById(R.id.btn_save);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
  }
  /**
   * Daten in eine Datei speichern
   * @param view
   */
  public void toSave(View view) {
    String fileName = mEt_filename.getText().toString();
    String fileContent = mEt_filecontent.getText().toString();
    FileService service = new FileService(getApplicationContext());
    boolean isSucceed = service.save(fileName, fileContent);
    if(isSucceed){
      Toast.makeText(getApplicationContext(), "Herzlichen Glückwunsch, das Speichern der Datei war erfolgreich!", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(getApplicationContext(), "Entschuldigung, das Speichern der Datei ist fehlgeschlagen!", Toast.LENGTH_SHORT).show();
    }
  }
  public void getFile(View view){
    String fileName = mEt_filename.getText().toString();
    FileService service = new FileService(getApplicationContext());
    String fileContent = service.getFile(fileName);
    if(fileContent != null || !fileContent.equals("")) {
      mEt_filecontent.setText(fileContent);
    } else {
      Toast.makeText(getApplicationContext(), "Entschuldigung, das Lesen der Datei ist fehlgeschlagen!", Toast.LENGTH_SHORT).show();
    }
  }
}

Fühlen Sie sich verwirrt über den Code darin? Was ist das für eine Klasse, FileService?

Tatsächlich ist FileService unsere Geschäftslogikklasse, deren Hauptfunktion darin besteht, uns zu helfen, Schreib- und Lesevorgänge für Dateien zu realisieren. Nachfolgend finden Sie auch den Code.

package com.mark.service;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
public class FileService {
  //android.content.Context ist eine Klasse, die von Android bereitgestellt wird, um schnell Datei-Ausgabestrom zu erhalten. Beachten Sie, dass das Argument kein Pfad sein kann, sondern nur der Dateiname sein muss.
  private Context mContext;
  public FileService(Context context) {
    this.mContext = context;
  }
  /**
   * Eine Methode zum Speichern von Dateien
   * @param fileName
   * @param fileContent
   * @return
   */
  public boolean save(String fileName, String fileContent) {
    try {
      //Wenn Sie den Modus Context.MODE_PRIVATE verwenden, ist nur der Zugriff auf diese Datei durch die aktuelle Anwendung erlaubt und Daten werden in überlappende Weise hinzugefügt.
      FileOutputStream fos = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
      fos.write(fileContent.getBytes());
      fos.close();
      return true;
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  /**
   * 获取之前保存过的文件的详细信息
   * @param fileName
   * @return
   */
  public String getFile(String fileName) {
    String fileContent = "";
    try{
      FileInputStream fis = mContext.openFileInput(fileName);
      byte[] buf = new byte[1024];
      int len;
      ByteArrayOutputStream bais = new ByteArrayOutputStream();
      while((len = fis.read(buf))!= -1{
        bais.write(buf, 0, len);
      }
      byte[] data = bais.toByteArray();
      fileContent = new String(data);
      fis.close();
      return fileContent;
    }
      e.printStackTrace();
      return "对不起,读取文件失败!";
    }
  }
}

业务类的分析

现在开始进入正题了。这个小项目的核心就在于这个业务类,原因如下:

  1. Context:Android自带的上下文类,方便获得文件流对象
  2. 在读取文件方法中使用到了ByteArrayOutputStream类,这一点是很重要的,如果只是单纯的使用字符串来读取存储的文件的话,就会因为序列化的问题而出现不了目标数据。
  3. 使用了返回值来对操作的结果进行了“反馈”,方便为用户提供友好的界面和使用体验。

核心

分层的思想,不同的功能的类放置到不同的包内,这样既方便程序的调试,也方便今后的代码维护。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Gefällt mir