欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android文件保存 博客分类: android android文件保存 

程序员文章站 2024-03-12 10:26:32
...

主界面 Activity

package com.example.save;

import com.example.util.Service;

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

public class Activity009 extends Activity {

	private Button b1;
	private EditText et1;
	private EditText et2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity009);
        b1 = (Button) findViewById(R.id.b1);
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        
        b1.setText("保存");
        b1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String filename = et1.getText().toString();
				String content = et2.getText().toString();
				Service service = new Service(Activity009.this);
				try {
					service.save(filename, content);
					Toast.makeText(Activity009.this, "保存成功", Toast.LENGTH_SHORT).show();		
				} catch (Exception e) {
					Toast.makeText(Activity009.this, "保存失败", Toast.LENGTH_SHORT).show();		
					e.printStackTrace();
				}
			}
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_activity009, menu);
        return true;
    }
}

 

Util 包中 Service 工具类

package com.example.util;

 import java.io.FileOutputStream;

import android.content.Context;

public class Service {
	private Context context ;
	public Service(Context context){
		this.context = context;
	}
	
	public void save(String filename ,String content) throws Exception{
		FileOutputStream out = context.openFileOutput(filename, context.MODE_PRIVATE);//private模式,对原文件进行覆盖,只有本应用能对该文件进行操作  //Append模式 ,检查文件是否存在,存在追加,不存在创建;只有本应用能对该文件进行操作。//Readable 可被其它文件读取 //writeable 可被其它文件写入
		out.write(content.getBytes());
	}
	
}
		out.write(content.getBytes());
	}
	
}