Android程序:程序中的文件读写实例

本文介绍了一个简单的Android应用程序,该程序实现了文件的读取和写入功能。通过使用Java语言,程序可以在Android设备上创建、读取和写入文本文件。具体实现包括:通过按钮触发文件写入操作,并将EditText中输入的内容保存到文件;读取文件内容并显示在TextView中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class MainActivity extends Activity {
    EditText text;
    TextView content;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText) findViewById(R.id.editText);
        content = (TextView) findViewById(R.id.contentView);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                WriteFile(text.getText().toString());
                content.setText(ReadFile());
            }
        });
    }

    public void WriteFile(String content) {
        try {
            //获取文件的输出流,若没有该文件则会自动创建
            FileOutputStream fos = openFileOutput("a.txt", MODE_PRIVATE);
            fos.write(content.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String ReadFile() {
        StringBuffer content = new StringBuffer();

        try {
            //创建一个输入流
            BufferedReader br=new BufferedReader(new InputStreamReader(openFileInput("a.txt")));
            String line = null;
            while((line=br.readLine())!=null){
                //拼接后加入换行符
                content.append(line+"\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content.toString();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值