Android---02---文件的保存与读取

数据存储与访问


很多时候我们开发的软件需要对处理后的数据进行存储,以供再次访问,Android为数据存储提供了如下几种方式:

·文件
·SharedPreferences(参数)
·SQLite数据库
·内容提供者(Content provider)
·网络

下面演示文件的存储与读取:



activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/text1" />

    <EditText
        android:id="@+id/filename"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="abc.txt" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="文件内容" />

    <EditText
        android:id="@+id/filecontent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minLines="3" />

    <Button
        android:id="@+id/myButtonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存" />

    <Button
        android:id="@+id/myButtonRead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取" />

</LinearLayout>



FileServise.java

//getbytes  得到的默认是U-8
package com.example.service;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import android.content.Context;

public class FileServise {
	/**
	 * 保存文件
	 * 
	 * @param filename
	 *            文件名称
	 * @param filecontent
	 *            文件内容
	 * @return
	 */

	private Context context;

	public FileServise(Context context) {
		super();
		this.context = context;
	}

	public void savefile(String filename, String filecontent)
			throws IOException {

		/*
		 * IO 技术 看过我的JAVASE IO流的 写起来很轻松,不过这里使用安卓的Context 对象可以快速得到输出流 第二个参数是
		 * 私有操作模式,创建出来的文件只能被本应用访问。 同时,采用私有模式创建的文件, 会覆盖源文件的内容。
		 */

		FileOutputStream fos = context.openFileOutput(filename,
				Context.MODE_PRIVATE);
		fos.write(filecontent.getBytes());
		fos.close();

	}

	/**
	 * 文件读取
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public String readfile(String filename) throws IOException {

		FileInputStream fis = context.openFileInput(filename);
		// 写入内存中的方法
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		// 获取
		byte[] data = baos.toByteArray();
		return new String(data);
	}

}






MainActivity.java
package com.example.androidfile;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.service.FileServise;

public class MainActivity extends Activity {

	private Button btns = null;
	private Button btnr = null;
	private EditText name = null;
	private EditText content = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btns = (Button) findViewById(R.id.myButtonSave);
		btnr = (Button) findViewById(R.id.myButtonRead);
		name = (EditText) findViewById(R.id.filename);
		content = (EditText) findViewById(R.id.filecontent);
		btns.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String filename = name.getText().toString();
				String filecontent = content.getText().toString();
				FileServise fs = new FileServise(MainActivity.this);
				try {
					fs.savefile(filename, filecontent);
					Toast.makeText(MainActivity.this, "保存完成",
							Toast.LENGTH_SHORT).show();
				} catch (IOException e) {
					Toast.makeText(MainActivity.this, "保存失败",
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}

			}
		});
		btnr.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				FileServise fs = new FileServise(MainActivity.this);
				try {

					Toast.makeText(MainActivity.this, fs.readfile("abc.txt"),
							Toast.LENGTH_SHORT).show();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

}



经测试,顺利的完成文件的存储与读取




2,存储入SD卡中



首先在Manifest中写入权限

<!-- 在SDCard中创建于删除文件的权限 -->  
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
<!-- 往SDCard中写入数据的权限 -->  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  


然后编写方法

//写入SD卡,可以由任何文件读和写的,因为SDCard不受权限控制
	public void saveToSDCard(String filename, String filecontent)
			throws IOException
	{
		//Environment.getExternalStorageDirectory() 获取SD卡路径
		File file=new File(Environment.getExternalStorageDirectory(),filename);
		FileOutputStream fos=new FileOutputStream(file);
		fos.write(filecontent.getBytes());
		fos.close();
	}


改造保存方法
public void onClick(View v) {
				String filename = name.getText().toString();
				String filecontent = content.getText().toString();
				FileServise fs = new FileServise(MainActivity.this);
				try {
					//判断SD卡是否插上并且可以读写
					if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
					{
					fs.saveToSDCard(filename, filecontent);
					
					Toast.makeText(MainActivity.this, "保存完成",
							Toast.LENGTH_SHORT).show();
					}
					else
						Toast.makeText(MainActivity.this, "SDCarderror",
								Toast.LENGTH_SHORT).show();
				} catch (IOException e) {
					Toast.makeText(MainActivity.this, "保存失败",
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}

			}

文件存入SD卡中。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值