Android创建读取文件demo

版权声明:欢迎转载,有问题劳烦指出 https://blog.csdn.net/qq_33592002/article/details/88109025

主要使用读取文件FileInputStream 的
read([文件名])方法.
在new对象的时候传入一个文件名.

和 写入文件FileOutputStream类write方法.
最后调用close()方法

代码

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

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

    }

    /**
     * 读取文件
     */
    public void readFile(View view) {// 很多初学者都会犯的错误
        try {
            FileInputStream fis = openFileInput("file.txt");
            byte[] bytes = new byte[20];
            fis.read(bytes);
            System.out.println("content:" + new String(bytes));
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入文件
     */
    public void writeFile(View view) {
        // 创建一个文件,程序自身可以读写
        try {
            FileOutputStream fos = openFileOutput("file.txt", Context.MODE_PRIVATE);
            fos.write("data".getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

布局文件

<?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:onClick="writeFile"
        android:text="写入"
        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:onClick="readFile"
        android:text="读取"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/bt_write" />
</android.support.constraint.ConstraintLayout>

猜你喜欢

转载自blog.csdn.net/qq_33592002/article/details/88109025