基于文件流的读取与写入是Android平台上的数据存取方式之一。
在Android中,可以通过Context.openFileInput和Context.openFileOutput来分别获取FileInputStream和FileOutputStream。
openFileInput(String fileName); 打开应用程序私有目录下的指定私有文件以读入数据,返回一个FileInputStream对象。
openFileOutput(String name,int mode);打开应用程序私有目录下的指定私有文件以写入数据,返回一个FileOutputStream对象,如果文件不存在就创建这个文件。
java文件:
package zy.just.com.fileinputorfileoutput; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import org.apache.http.util.EncodingUtils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { public static final String ENCODING="UTF-8";//常量,代表编码格式。 String fileName="test.txt";//文件名称 String message="你好,这是一个关于文件I/O的示例。";//写入和读出的数据信息 private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); writeFileData(fileName, message);//创建文件并写入数据 String result= readFileData(fileName);//获得从文件读入的数据 tv = (TextView) findViewById(R.id.tv); tv.setText(result); } /** * 方法:向指定文件中写入指定的数据 * @param fileName * @param message */ public void writeFileData(String fileName,String message){ try { FileOutputStream fos = openFileOutput(fileName,MODE_PRIVATE);//获得FileOutputStream对象 byte[] bytes = message.getBytes();//将要写入的字符串转换为byte数组 fos.write(bytes);//将byte数组写入文件 fos.close();//关闭FileOutputStream对象 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 打开指定文件,读取其数据,返回字符串对象 * @param fileName * @return */ public String readFileData(String fileName){ String result = ""; try { FileInputStream fin = openFileInput(fileName);//获得FileInputStream对象 int length = fin.available();//获取文件长度 byte[] buffer = new byte[length];//创建byte数组用于读入数据 fin.read(buffer); result = EncodingUtils.getString(buffer,ENCODING);//将byte数组转换成指定格式的字符串 fin.close();//关闭文件输入流 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }xml布局文件:
<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" tools:context=".MainActivity"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout>
运行结果: