Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓文件的讀和寫的實現

安卓文件的讀和寫的實現

編輯:關於Android編程

說明:

文件保存路徑為安卓默認路徑,/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;
	}
}
 


 

 

//

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved