基本信息
源码名称:android 文件读写 例子源码下载
源码大小:1.28M
文件格式:.rar
开发语言:Java
更新时间:2015-03-07
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 1 元 
   源码介绍


package lqf.fileio;

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

import org.apache.http.util.EncodingUtils;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				saveInputDataToFile();
				
			}
		});
		
		findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadDataFromFile();
				
			}
		});
	}

	protected void loadDataFromFile() {
		try {
			FileInputStream fis = openFileInput("test.txt");
			//create byte[] use save the read out data
			byte[] buffer = new byte[1024];
			//read data and save in buffer
			fis.read(buffer);
			//encoding the data read from file
			String fileContent = EncodingUtils.getString(buffer, "UTF-8");
			((TextView)findViewById(R.id.textView3)).setText(fileContent);
			((TextView)findViewById(R.id.textView3)).setTextColor(Color.BLUE);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	protected void saveInputDataToFile() {
		try {
			FileOutputStream fos = openFileOutput("test.txt", Context.MODE_APPEND);
			
			//get the content from edittext
			
			String inputFileContent = ((EditText)findViewById(R.id.editText1)).getText().toString().trim();
			//将字符串转化为byte数组
			fos.write(inputFileContent.getBytes());
			fos.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}