安卓文件的读和写的实现

说明:

文件保存路径为安卓默认路径,/data/应用包名(全名)/files

一、activity

package com.example.filerw;

import com.example.server.FileServer;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	private EditText contentEdit;
	private String file_name="file.txt";
	private FileServer fileServer;
	private TextView showText;

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

		contentEdit = (EditText)findViewById(R.id.content);
		showText = (TextView)findViewById(R.id.showText);

		fileServer = new FileServer(getApplicationContext());
	}

	public void MainClick(View v){
		switch (v.getId()) {
		case R.id.save:
			String str = contentEdit.getText().toString();
			fileServer.save(file_name, str);
			break;

		case R.id.read:
			String show = fileServer.read(file_name);
			showText.setText(show);
			break;

		default:
			break;
		}
	}
	//菜单
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}

二、主要实现代码

package com.example.server;

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

import org.apache.http.util.EncodingUtils;

import android.content.Context;

public class FileServer {
	private Context context;
	private FileInputStream in;
	private FileOutputStream out;

	public FileServer(Context context){
		this.context = context;
	}
	/**
	 * 保存
	 * @param name
	 */
	public void save(String name,String content){
		try {
			out = context.openFileOutput(name, Context.MODE_PRIVATE);
			out.write(content.getBytes());
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
	/**
	 * 读文件
	 * @param name
	 * @return
	 */
	public String read(String name){
		String file_content = null;
		try {
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			in = context.openFileInput(name);//具有缓冲实例的打开文件
			byte[] buf = new byte[1024];
			while((in.read(buf))!=-1){
				byteOut.write(buf);//将读出来的数据写到缓存中
			}
			file_content = EncodingUtils.getString(byteOut.toByteArray(),"GBK");//转码

			byteOut.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (Exception e) {
			System.out.println(e.toString());
		}
		return file_content;
	}
}

三、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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:padding="0dp"
    >
    <EditText
        android:id="@+id/content"
  		android:inputType="text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入内容"
        android:textSize="16sp"
        android:background="@drawable/edit_xmlbg"
        android:minHeight="30dp"
        />
    <TextView
        android:id="@+id/showText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/content"
        />
    <Button
        android:id="@+id/save"
        android:onClick="MainClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="save"
        android:layout_alignParentBottom="true"
        />
	<Button
        android:id="@+id/read"
        android:onClick="MainClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="read"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/save"
        />
</RelativeLayout>

//

时间: 2024-08-29 14:48:34

安卓文件的读和写的实现的相关文章

java中文件的读与写

最近一直在学习java中如何读取和写出文件,看了java API之后,发现在java.io中有很多关于文件读与写的类,下面就介绍几个经常用到的. 首先是:InputStream和OutputStream,API中说它俩是所有抽象类表示字节输入输出流的超类,所以在它们下面派生了很多子类.例如:FileInputStream和OutputStream等等.这些类都是以单字节的形式读入数据的,所以如果读入的数据中有中文字符,那么就会出现中文乱码现象. 其次是:Reader和Writer,这两个类是用于

利用FileChannel完成文件的读、写、复制

内容:通过NIO中的FileChannel完成文件的读.写.复制. public class NioFileCopy { private RandomAccessFile aFile = null; private FileChannel inChannel = null; private final ByteBuffer buf = ByteBuffer.allocate(1024); public void doWrite() throws IOException { aFile = new

WPF程序中App.Config文件的读与写

原文:WPF程序中App.Config文件的读与写 WPF程序中的App.Config文件是我们应用程序中经常使用的一种配置文件,System.Configuration.dll文件中提供了大量的读写的配置,所以它是一种高效的程序配置方式,那么今天我就这个部分来做一次系统性的总结. App.Config文件是系统默认的应用程序配置文件,在我们使用后进行编译时会生成"程序集名称+.exe.config"文件,其本质上也是一个XML文件,在我们的应用程序中添加应用程序配置文件后,默认生成下

python文件处理-读、写

Python中文件处理的操作包括读.写.修改,今天我们一起来先学习下读和写操作. 一.文件的读操作 例一: #文件读操作 f = open(file="first_blog.txt",mode = 'r',encoding='gbk') #'r'表示只读模式(打开仍然为文件),encoding = 'gbk'表示原文件的存储格式为'gbk',打开时必须告诉程序将gbk转成unicode(python3编码默认Unicode) data = f.read() # 读取所有内容,内容是已经

python 文件操作读、写、追加的区别

打开文件的常用模式有: r ,只读模式[默认] w,只写模式[不可读:不存在则创建:存在则清空内容:] a, 追加模式[可读: 不存在则创建:存在则只追加内容:] "+" 表示可以同时读写某个文件 r+, 读写[可读,可写][可理解为先读后写,不擦除原文件内容,指针在0] w+,写读[可读,可写][可理解为先写后读,擦除原文件内容,指针在0] a+, 写读[可读,可写][不擦除原文件内容,但指针直接到最后,读取原内容先重置指针] 模式 可做操作 若文件不存在 是否覆盖 指针位置 r 只

第八天 文件的读,写,追加,读写,写读,seek()光标的移动,修改文件以及另一种打开文件的方式

主要内容:    1.初始文件操作 2.只读( r,rb ) 3.只写( w,wb ) 4.追加( a ,ab) 5.读写( r+ ) 6.写读( w+ ) 7.追加写读 ( a+ ) 8.其他操作方法 9.文件的修改以及另一种打开文件句柄的方式 一.初始文件的操作    使用python来读写文件是非常简单的操作. 我们使用open()函数来打开?个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. 根据打开方式的不同能够执行的操作也会有相应的差异. 打开文件的方式: r,

9.python-ini文件使用(读和写)

注意事项: 1.读文件: read(filename):读取ini文件中的内容 sections():得到所有section,返回列表形式 options(section):得到给定section的所有option items(section):得到指定section的所有key-value get(section,option):得到section中的option值,返回str类型 get(section,option):得到section中的option值,返回int类型 2.写文件: ad

python-ini文件使用(读和写)

注意事项: 1.读文件: read(filename):读取ini文件中的内容 sections():得到所有section,返回列表形式 options(section):得到给定section的所有option items(section):得到指定section的所有key-value get(section,option):得到section中的option值,返回str类型 get(section,option):得到section中的option值,返回int类型 2.写文件: ad

Python 2.7.9 Demo - ini文件的读、写

ini文件 [weixin_info] hello = Nick Huang #coding=utf-8 #!/usr/bin/python import ConfigParser; cp = ConfigParser.ConfigParser(); cp.read('027.99.config.ini'); hello = cp.get('weixin_info', 'hello'); print hello; #coding=utf-8 #!/usr/bin/python import Co