Android文件操作中的openFileOutput和openFileInput的操作
openFileOutput用于往文件中写入内容,openFileInput用于读出文件中的内容
openFileOutput(String name,MODE),第一个参数name时文件的名字,不可以携带“/”,如果没有这个文件那那么Android会自己创建一个文件,创建的文件保存在/data/data/<package name>/files目录下面。第二个参数用于操作指定的模式,有四种模式,不过常用的有两种,另外两种好像淘汰了?这两种模式为:
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
首先设置一个简单的布局文件,只有两个按钮,分别是写入、读取
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/bt_write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginLeft="8dp" android:layout_marginTop="8dp" android:text="写入" android:onClick="writeFile" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/bt_read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginLeft="8dp" android:layout_marginTop="8dp" android:text="读取" android:onClick="readFile" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/bt_write" /> </android.support.constraint.ConstraintLayout>
写入文件的部分代码如下:
public void writeFile(View view) { // 创建一个文件,程序自身可以读写 try { FileOutputStream fos = openFileOutput("file.txt", Context.MODE_PRIVATE); fos.write("hello".getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
读取文件的代码如下:
public void readFile(View view) { //很多初学者会犯的错误 try { FileInputStream fis = openFileInput("file.txt"); byte[] bytes = new byte[20]; /*BufferedInputStream bis=new BufferedInputStream(fis);*/ int len =0; /*fis.read(bytes);*/ while((len =fis.read(bytes))!= -1) { String str = new String(bytes,0,len); System.out.println("content:" + str); } fis.close(); } catch (Exception e) { e.printStackTrace(); } } }